向pandas DataFrame对象添加空列的最简单方法是什么?我碰到的最好的是

df['foo'] = df.apply(lambda _: '', axis=1)

有没有更合理的方法?


当前回答

为了补充DSM的答案,并在这个相关问题的基础上,我将这种方法分为两种情况:

添加单列:只需为新列分配空值,例如df['C'] = np.nan 添加多个列:我建议使用pandas的.reindex(columns=[…])方法将新列添加到数据帧的列索引中。这也适用于使用.reindex(rows=[…])添加多个新行。注意,更新版本的Pandas (v>0.20)允许您指定axis关键字,而不是显式地分配给列或行。

下面是一个添加多列的例子:

mydf = mydf.reindex(columns = mydf.columns.tolist() + ['newcol1','newcol2'])

or

mydf = mydf.reindex(mydf.columns.tolist() + ['newcol1','newcol2'], axis=1)  # version > 0.20.0

你也可以总是连接一个新的(空的)数据框架到现有的数据框架,但这对我来说不像python式的:)

其他回答

我喜欢:

df['new'] = pd.Series(dtype='int')

# or use other dtypes like 'float', 'object', ...

如果您有一个空的数据框架,这个解决方案确保没有只包含NaN的新行被添加。

指定dtype并不是必须的,但是如果没有指定dtype,更新的Pandas版本会产生DeprecationWarning。

我寻找这样一个解决方案的原因只是在多个df之间添加空格,这些df已经使用pd按列连接。Concat函数,然后使用xlsxwriter写入excel。

df[' ']=df.apply(lambda _: '', axis=1)
df_2 = pd.concat([df,df1],axis=1)                #worked but only once. 
# Note: df & df1 have the same rows which is my index. 
#
df_2[' ']=df_2.apply(lambda _: '', axis=1)       #didn't work this time !!?     
df_4 = pd.concat([df_2,df_3],axis=1)

然后将第二个lambda调用替换为

df_2['']=''                                 #which appears to add a blank column
df_4 = pd.concat([df_2,df_3],axis=1)

我测试的输出是使用xlsxwriter到excel。 Jupyter空白列看起来和excel一样,虽然没有xlsx格式。 不知道为什么第二个Lambda调用没有工作。

如果您想从列表中添加列名

df=pd.DataFrame()
a=['col1','col2','col3','col4']
for i in a:
    df[i]=np.nan

一个更简单的解决方案是:

df = df.reindex(columns = header_list)                

其中“header_list”是你想要显示的标题列表。

列表中包含的任何标题,如果在数据帧中没有找到,将在下面添加空白单元格。

因此,如果

header_list = ['a','b','c', 'd']

然后将c和d添加为带空白单元格的列

很抱歉我一开始没有解释清楚我的答案。还有另一种方法可以将新列添加到现有数据框架中。 第一步,创建一个新的空数据帧(包含数据帧中的所有列,加上您想添加的新列或少数列),称为df_temp 第二步,结合df_temp和你的数据帧。

df_temp = pd.DataFrame(columns=(df_null.columns.tolist() + ['empty']))
df = pd.concat([df_temp, df])

这可能是最好的解决方案,但这是思考这个问题的另一种方式。

我使用这种方法的原因是因为我总是得到这样的警告:

: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df["empty1"], df["empty2"] = [np.nan, ""]

太好了,我找到了禁用警告的方法

pd.options.mode.chained_assignment = None