我应用了一些函数并为Pandas数据帧的现有列生成新的列值.但是df['col1'] = new_list无法为列分配新列表.这是错误的方式,应用此类操作的准确方法是什么?
我想将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 …