How to add an empty column to a dataframe?
已经部分覆盖了。
接受的答案中的dtype of df["D"] = np.nan
是dtype=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 []
答案 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)