Python pandas将列表插入单元格

2022-01-09 00:00:00 python pandas dataframe list insert

问题描述

我有一个列表abc"和一个数据框df":

I have a list 'abc' and a dataframe 'df':

abc = ['foo', 'bar']
df =
    A  B
0  12  NaN
1  23  NaN

我想将列表插入单元格 1B,所以我想要这个结果:

I want to insert the list into cell 1B, so I want this result:

    A  B
0  12  NaN
1  23  ['foo', 'bar']

我可以这样做吗?

1) 如果我使用这个:

1) If I use this:

df.ix[1,'B'] = abc

我收到以下错误消息:

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

因为它试图将列表(包含两个元素)插入行/列而不是单元格.

because it tries to insert the list (that has two elements) into a row / column but not into a cell.

2) 如果我使用这个:

2) If I use this:

df.ix[1,'B'] = [abc]

然后它会插入一个列表,其中只有一个元素是 'abc' 列表( [['foo', 'bar']] ).

then it inserts a list that has only one element that is the 'abc' list ( [['foo', 'bar']] ).

3) 如果我使用这个:

3) If I use this:

df.ix[1,'B'] = ', '.join(abc)

然后它插入一个字符串:( foo, bar ) 但不是一个列表.

then it inserts a string: ( foo, bar ) but not a list.

4) 如果我使用这个:

4) If I use this:

df.ix[1,'B'] = [', '.join(abc)]

然后它插入一个列表,但它只有一个元素( ['foo, bar'] )但不是我想要的两个( ['foo', 'bar']).

then it inserts a list but it has only one element ( ['foo, bar'] ) but not two as I want ( ['foo', 'bar'] ).

感谢您的帮助!

我的新数据框和旧列表:

My new dataframe and the old list:

abc = ['foo', 'bar']
df2 =
    A    B         C
0  12  NaN      'bla'
1  23  NaN  'bla bla'

另一个数据框:

df3 =
    A    B         C                    D
0  12  NaN      'bla'  ['item1', 'item2']
1  23  NaN  'bla bla'        [11, 12, 13]

我想将 'abc' 列表插入 df2.loc[1,'B'] 和/或 df3.loc[1,'B'].

I want insert the 'abc' list into df2.loc[1,'B'] and/or df3.loc[1,'B'].

如果数据框的列仅包含整数值和/或 NaN 值和/或列表值,则将列表插入单元格可以完美地工作.如果数据框的列仅包含字符串值和/或 NaN 值和/或列表值,则将列表插入单元格可以完美地工作.但是,如果数据框包含具有整数和字符串值的列以及其他列,那么如果我使用它,则会出现错误消息: df2.loc[1,'B'] = abcdf3.loc[1,'B'] = abc.

If the dataframe has columns only with integer values and/or NaN values and/or list values then inserting a list into a cell works perfectly. If the dataframe has columns only with string values and/or NaN values and/or list values then inserting a list into a cell works perfectly. But if the dataframe has columns with integer and string values and other columns then the error message appears if I use this: df2.loc[1,'B'] = abc or df3.loc[1,'B'] = abc.

另一个数据框:

df4 =
          A     B
0      'bla'  NaN
1  'bla bla'  NaN

这些插入工作完美:df.loc[1,'B'] = abcdf4.loc[1,'B'] = abc..p>

These inserts work perfectly: df.loc[1,'B'] = abc or df4.loc[1,'B'] = abc.


解决方案

df3.set_value(1, 'B', abc) 适用于任何数据帧.注意B"列的数据类型.例如.列表不能插入浮点列,在这种情况下 df['B'] = df['B'].astype(object) 可以提供帮助.

df3.set_value(1, 'B', abc) works for any dataframe. Take care of the data type of column 'B'. Eg. a list can not be inserted into a float column, at that case df['B'] = df['B'].astype(object) can help.

相关文章