要向元素类型为list的DataFrame中的每个list添加元素,可以使用apply函数来实现。apply函数可以对DataFrame中的每个元素应用一个自定义的函数。

下面是一个示例代码,假设DataFrame为df,列名为'list_column',要向每个list添加元素'new_element':

import pandas as pd

# 示例DataFrame
df = pd.DataFrame({'list_column': [[1, 2], [3, 4], [5, 6]]})

# 自定义函数,用于向list中添加元素
def add_element(lst):
    lst.append('new_element')
    return lst

# 使用apply函数应用自定义函数到每个list
df['list_column'] = df['list_column'].apply(add_element)

print(df)

输出结果为:

    list_column
0  [1, 2, new_element]
1  [3, 4, new_element]
2  [5, 6, new_element]

可以看到,每个list都被成功添加了'new_element'

元素类型为list的df向每个list添加元素

原文地址: https://www.cveoy.top/t/topic/iw9t 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录