如何将整个列表分配给 pandas 数据框的每一行 [英] how to assign an entire list to each row of a pandas dataframe
本文介绍了如何将整个列表分配给 pandas 数据框的每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框和一个列表
I have a dataframe and a list
df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6]})
mylist= [10,20,30,40,50]
我想在数据帧的每一行中都有一个列表作为元素。如果我确实喜欢此处,
I would like to have a list as element in each row of a dataframe. If I do like here,
df['C'] = mylist
Pandas尝试每行广播一个值,所以出现错误值的长度与索引的长度不匹配
。
Pandas is trying to broadcast one value per row, so I get an error Length of values does not match length of index
.
A B C
0 1 4 [10,20,40,50]
1 2 5 [10,20,40,50]
2 3 6 [10,20,40,50]
推荐答案
首先,我认为在熊猫中使用 list
s不是好主意。
First I think working with list
s in pandas is not good idea.
但是可以通过列表理解:
But it is possible by list comprehension:
df['C'] = [mylist for i in df.index]
#another solution
#df['C'] = pd.Series([mylist] * len(df))
print (df)
A B C
0 1 4 [10, 20, 30, 40, 50]
1 2 5 [10, 20, 30, 40, 50]
2 3 6 [10, 20, 30, 40, 50]
这篇关于如何将整个列表分配给 pandas 数据框的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文