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

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

有没有更合理的方法?


当前回答

如果你有一个列列表,你想要为空,你可以使用赋值,然后理解字典,然后字典解包。

>>> df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]})
>>> nan_cols_name = ["C","D","whatever"]
>>> df.assign(**{col:np.nan for col in nan_cols_name})

   A  B   C   D  whatever
0  1  2 NaN NaN       NaN
1  2  3 NaN NaN       NaN
2  3  4 NaN NaN       NaN

如果希望不同列有不同的值,还可以在解包的字典中解包多个字典。

df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]})
nan_cols_name = ["C","D","whatever"]
empty_string_cols_name = ["E","F","bad column with space"]
df.assign(**{
    **{col:np.nan for col in my_empy_columns_name}, 
    **{col:"" for col in empty_string_cols_name}
            }
         )

其他回答

你可以这样做

df['column'] = None #This works. This will create a new column with None type
df.column = None #This will work only when the column is already present in the dataframe 

我寻找这样一个解决方案的原因只是在多个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": [1,2,3], "B": [2,3,4]})
>>> df
   A  B
0  1  2
1  2  3
2  3  4

df1 = pd.DataFrame(columns=['C','D','E'])
df = df.join(df1, how="outer")

>>>df
    A   B   C   D   E
0   1   2   NaN NaN NaN
1   2   3   NaN NaN NaN
2   3   4   NaN NaN NaN

然后对列做任何你想做的事情 pd.Series.map pd.Series.fillna (), () 等。

如果我理解正确,assignment应该填写:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]})
>>> df
   A  B
0  1  2
1  2  3
2  3  4
>>> df["C"] = ""
>>> df["D"] = np.nan
>>> df
   A  B C   D
0  1  2   NaN
1  2  3   NaN
2  3  4   NaN

下面的代码解决了“如何向现有数据框架中添加n个空列”的问题。为了将类似问题的解决方案保存在一个地方,我在这里添加了它。

方法1(创建64个附加列,列名从1到64)

m = list(range(1,65,1)) 
dd=pd.DataFrame(columns=m)
df.join(dd).replace(np.nan,'') #df is the dataframe that already exists

方法2(创建64个附加列,列名从1到64)

df.reindex(df.columns.tolist() + list(range(1,65,1)), axis=1).replace(np.nan,'')