相关疑难解决方法(0)

如何将熊猫列的值设置为列表

我想将pandas列的值设置为字符串列表。但是,我这样做没有成功,因为大熊猫将列值视为可迭代值,并且得到了:ValueError: Must have equal len keys and value when setting with an iterable。

这是MWE

>> df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]})
>> df
col1    col2
0   1   4
1   2   5
2   3   6

>> df['new_col'] = None
>> df.loc[df.col1 == 1, 'new_col'] = ['a', 'b']
ValueError: Must have equal len keys and value when setting with an iterable
Run Code Online (Sandbox Code Playgroud)

我试图将设置dtype为listusing df.new_col = df.new_col.astype(list),但这也不起作用。

我想知道什么是正确的方法。


编辑

这里提供的答案:Python的大熊猫插入列表进入细胞使用at …

python pandas

3
推荐指数
2
解决办法
3175
查看次数

标签 统计

pandas ×1

python ×1