【pandas】将 列表写入dataframe里的某一个单元格

问题:
loc 将list 写入dataframe里的某一个单元格,会报错Must have equal len keys and value when setting with an iterable

问题expamle
I have a list ‘abc’ and a dataframe ‘df’:

abc = [‘foo’, ‘bar’]
df =
A B
0 12 NaN
1 23 NaN
I want to insert the list into cell 1B, so I want this result:

A  B

0 12 NaN
1 23 [‘foo’, ‘bar’]
Ho can I do that?

  1. If I use this:

df.ix[1,‘B’] = abc
I get the following error message:

ValueError: Must have equal len keys and value when setting with an iterable

解决办法: 用at而不是用loc
df = pd.DataFrame(data={‘A’: [1, 2, 3], ‘B’: [‘x’, ‘y’, ‘z’]})

df.at[1, ‘B’] = [‘m’, ‘n’]

df =
A B
0 1 x
1 2 [m, n]
2 3 z

I think this is because at always refers to a single value, while loc can refer to values as well as rows and columns.

解答方案来源:https://stackoverflow.com/questions/26483254/python-pandas-insert-list-into-a-cell

如何实现:pandas某列,若值为空,则用 空列表(list)填充

实现方法如下:

list_x = []  # type(list_x)
df1.loc[df1[df1['字段'].isnull()].index, '字段'] = '#a'
df1['字段'] = df1.apply(lambda x: list_x if x.字段 == '#a' else x.字段, axis=1)
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值