熊猫将对象的空列添加到数据框

时间:2018-07-06 03:22:07

标签: pandas object dataframe

How to add an empty column to a dataframe?

已经部分覆盖了。

接受的答案中的dtype of df["D"] = np.nandtype=numpy.float64

有没有一种方法可以在每个单元格中初始化一个空列表?

尝试df["D"] = [[]] * len(df),但所有值都指向同一对象,将一个值设置为一个值会将它们全部设置。

df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]})
df

   A  B
0  1  2
1  2  3
2  3  4


df["D"] = [[]] * len(df)
df
   A  B   D
0  1  2  []
1  2  3  []
2  3  4  []


df['D'][1].append(['a','b','c','d'])
df
   A  B               D
0  1  2  [[a, b, c, d]]
1  2  3  [[a, b, c, d]]
2  3  4  [[a, b, c, d]]

想要

   A  B               D
0  1  2  []
1  2  3  [[a, b, c, d]]
2  3  4  []

2 个答案:

答案 0 :(得分:5)

使用

df["D"] = [[] for _ in range(len(df))]

代替

df["D"] = [[]] * len(df) 

这样,您将为每行创建一个不同的[]


基本上[[] for _ in range(len(df))]list comprehension.,它为[]中的每个值创建一个range(len(df))

此代码与

具有相同的功能
l = []
for _ in range(len(df)):
    l.append([])

但是更快更简单,编写起来更加可读。

如果您想进一步了解列表理解,建议使用the answers for this question

如果您想进一步了解为什么在执行[[]] * len(df)时会发生这种行为,建议您使用the answers for this question

答案 1 :(得分:1)

创建列时,您是否只能传递列表列表?然后将列表值分配给一个临时变量,然后使用loc

将该列表分配给数据框中的一个字段
import pandas as pd

df = pd.DataFrame()
df['col A'] = [1,12,312,352]
df['col B'] = [[],[],[],[]]

ser = [1,4,5,6]
df.loc[2,'col B'] = ser
df

输出:

Click Here to View Image

这有帮助吗?这是您要找的吗?