【发布时间】:2019-03-04 06:23:38
【问题描述】:
我想将 pandas 列的值设置为字符串列表。但是,我这样做的努力没有成功,因为 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
我尝试使用df.new_col = df.new_col.astype(list) 将dtype 设置为list,但这也不起作用。
我想知道这里的正确方法是什么。
编辑
此处提供的答案:Python pandas insert list into a cell 使用 at 对我也不起作用。
【问题讨论】:
-
df.at[1, 'new_col'] = ['a', 'b'] -
为什么不添加 2 个新列而不是使用一个系列来保存列表?