如何将列表分配给Pandas Data Frame的现有列? [英] How to assign a list to existing column of Pandas Data Frame?

查看:79
本文介绍了如何将列表分配给Pandas Data Frame的现有列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应用了一些函数,并为Pandas数据框的现有列生成了新的列值.但是,df['col1'] = new_list无法将新列表分配给该列.是错误的方法,应用这种操作的准确方法是什么?

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 ?

推荐答案

如果列表的长度等于DataFrame中的行数,则应该起作用

It should work if length of the list is equal to the number of rows in the 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

如果您的列表比DataFrame短或长,那么您会收到错误Length of values does not match length of index.

If your list is shorter or longer than DataFrame, then you'll receive an error Length of values does not match length of index.

这篇关于如何将列表分配给Pandas Data Frame的现有列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆