問題描述
我有一個列表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'] = abc
或 df3.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'] = abc
或 df4.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.
這篇關于Python pandas將列表插入單元格的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!