python - 如何将熊猫列的值设置为列表
问题描述
我想将 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
我试图将其设置dtype
为list
使用df.new_col = df.new_col.astype(list)
,但也没有奏效。
我想知道这里的正确方法是什么。
编辑
此处提供的答案:Python pandas insert list into a cell usingat
对我也不起作用。
解决方案
不容易,一种可能的解决方案是创建助手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 数组的向量化功能。
推荐阅读
- python - 消除探索性数据分析 (EDA) 中的偏斜
- elasticsearch - 在 ElasticSearch 6.0.0 中使用特殊字符过滤
- maven - 如何更新 Intellij 中的 mapstruct 依赖项?
- math - 找到给定两条线的交点,每条线都通过两个以上的点
- scroll - Angular 11 - 无法使用虚拟滚动选择剑道网格中的网格行
- c++ - 如何在没有 sstream 的情况下接受带空格的输入并将其转换为 int 向量
- amazon-web-services - CUDNN_STATUS_NOT_INITIALIZED 使用 pip 但不使用 conda 安装 pytorch 时
- r - 比较 glms 时排除 nobs 不同的错误
- php - Symfony 5:将模板应用于特定自定义表单类型的所有字段
- c# - 如何设置仅在 Moq 4.13.1 中以严格模式返回任务的异步方法?