首页 > 解决方案 > Pandas DataFrame:通过使用新列迭代 df 向每个单元格添加一个列表不起作用

问题描述

带有一些列 a 和 b 的 DataFrame。
我现在想添加一个新列 c 应该包含列表(不同长度)。

df1 = pd.DataFrame({'a':[1,2,3], 'b':[5,6,7]})
new_col_init = [list() for i in range(len(df1)]
df1['c'] = pd.Series(new_col_init,dtype='object')
print(df1)

给出:

   a  b   c
0  1  5  []
1  2  6  []
2  3  7  []

为什么我无法执行以下操作:

for i in range(len(df1)):
    df1.loc[i,'c'] = [2]*i

这导致ValueError: cannot set using a multi-index selection indexer with a different length than the value.

但是,这有效:

df1['c'] = pd.Series([[2], [2,2], [2,2,2]])
print(df1)

结果:

    a   b   c
0   1   5   [2]
1   2   6   [2, 2]
2   3   7   [2, 2, 2]

有没有办法通过使用 for 循环迭代来分配列表?(我有很多其他的东西已经在那个循环中分配了,我现在需要添加新的列表)

标签: pythonpython-3.xpandas

解决方案


您可以使用.at

for i, idx in enumerate(df1.index, 1):
    df1.at[idx, "c"] = [2] * i

print(df1)

印刷:

   a  b          c
0  1  5        [2]
1  2  6     [2, 2]
2  3  7  [2, 2, 2]

推荐阅读