Python 如何将列表分配给 Pandas 数据框的现有列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19779015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to assign a list to existing column of Pandas Data Frame?
提问by erogol
I apply some functions and generate a new column values to a existing column of Pandas dataframe. However df['col1'] = new_list
does not work to assign new list to the column. Is it the wrong way and what is the accurate way to apply such operation ?
我应用了一些函数并为 Pandas 数据框的现有列生成一个新列值。但是df['col1'] = new_list
,无法将新列表分配给该列。这是错误的方法,应用这种操作的准确方法是什么?
回答by Roman Pekar
It should work if length of the list is equal to the number of rows in the DataFrame
如果列表的长度等于 DataFrame 中的行数,它应该可以工作
>>> df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6]})
>>> df['C'] = [10,20,30]
>>> df
A B C
0 1 4 10
1 2 5 20
2 3 6 30
If your list is shorter or longer than DataFrame, then you'll receive an error Length of values does not match length of index
.
如果您的列表比 DataFrame 短或长,那么您将收到错误消息Length of values does not match length of index
。