如何将列表分配给Pandas Data Frame的现有列?

ero*_*gol 7 python pandas

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

Rom*_*kar 8

如果列表的长度等于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
Run Code Online (Sandbox Code Playgroud)

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

  • 您没有在示例中重新分配列,而只是向其中添加新列。 (2认同)
  • 有没有办法用“missing”或“nan”或“Nan”或其他东西填充? (2认同)