【发布时间】:2022-01-08 23:42:16
【问题描述】:
给定一个数据框:
np.random.seed(0)
df = pd.DataFrame(np.random.randn(3, 3), columns=list('ABC'), index=[1, 2, 3])
df
A B C
1 1.764052 0.400157 0.978738
2 2.240893 1.867558 -0.977278
3 0.950088 -0.151357 -0.103219
添加包含常量值(例如 0)的新列的最简单方法是什么?
A B C new
1 1.764052 0.400157 0.978738 0
2 2.240893 1.867558 -0.977278 0
3 0.950088 -0.151357 -0.103219 0
这是我的解决方案,但我不知道为什么这会将 NaN 放入“新”列?
df['new'] = pd.Series([0 for x in range(len(df.index))])
A B C new
1 1.764052 0.400157 0.978738 0.0
2 2.240893 1.867558 -0.977278 0.0
3 0.950088 -0.151357 -0.103219 NaN
【问题讨论】:
-
如果你使用索引没问题。
df['new'] = pd.Series([0 for x in range(len(df.index))], index=df.index). -
另外,这里完全不需要列表理解。就做
[0] * len(df.index) -
@joris,我的意思是 df['new']=0 显示了为整个列分配零的正确原因,但它没有解释为什么我的第一次尝试插入 NaN。 Philip Cloud 在我接受的答案中回答了这个问题。
-
只需做
df['new'] = 0