问题:
用 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?
- 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)