首页 > 解决方案 > 如何使用熊猫在数据框中添加一个空列(不指定列名)?

问题描述

我有一个只有一列(无标题)的数据框。我想向它添加另一个具有相同行数的空列。

为了更清楚,目前,我的数据框的大小为 1050(因为只有一列),我希望新的大小为 1050*2,第二列完全为空。

标签: python-3.xpandasdataframe

解决方案


在 DataFrame 中的 pandas 中始终是列,因此对于由缺失值填充的新默认列,使用列的长度:

s = pd.Series([2,3,4])

df = s.to_frame()

df[len(df.columns)] = np.nan
#what is same for one column df like
#df[1] = np.nan
print (df)
   0   1
0  2 NaN
1  3 NaN
2  4 NaN

推荐阅读