首页 > 解决方案 > 如何将熊猫列的值设置为列表

问题描述

我想将 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

我试图将其设置dtypelist使用df.new_col = df.new_col.astype(list),但也没有奏效。

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


编辑

此处提供的答案:Python pandas insert list into a cell usingat对我也不起作用。

标签: pythonpandas

解决方案


不容易,一种可能的解决方案是创建助手Series

df.loc[df.col1 == 1, 'new_col'] = pd.Series([['a', 'b']] * len(df))
print (df)
   col1  col2 new_col
0     1     4  [a, b]
1     2     5     NaN
2     3     6     NaN

另一种解决方案,如果需要将缺失值也设置为空列表是使用列表理解:

#df['new_col'] = [['a', 'b'] if x == 1 else np.nan for x in df['col1']]

df['new_col'] = [['a', 'b'] if x == 1 else [] for x in df['col1']]
print (df)
   col1  col2 new_col
0     1     4  [a, b]
1     2     5      []
2     3     6      []

但是随后您将失去使用保存在连续内存块中的 NumPy 数组的向量化功能。


推荐阅读