python - 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 循环迭代来分配列表?(我有很多其他的东西已经在那个循环中分配了,我现在需要添加新的列表)
解决方案
您可以使用.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]
推荐阅读
- java - 如何在没有 break 语句的情况下键入 BinarySearch 方法 while-loop?
- laravel - vue dropzone中的Vue js自定义功能
- react-native - 将数据添加到 FlatList 始终显示第一个孩子
- python - 关于选民投票率的 Python 分配问题:类、对象和函数
- reactjs - 将参数传递给 firestore 集合
- excel - 缩短单元格,嵌套 Ifs Excel
- hyperledger-fabric - 链码实例化错误 /usr/bin/ld: 找不到 -lxxx
- java - 同步 textArea.clear() 后跟 textArea.setText() 不清除文本
- ajax - 在 Laravel 中使用 Ajax 进行分页
- python - 如何编写根据距中心的距离和边数在油漆中绘制规则图形的函数?