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

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

有没有更合理的方法?


当前回答

你可以这样做

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调用没有工作。

如果我理解正确,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

从v0.16.0开始,可以使用DF.assign()将新列(单个/多个)分配给DF。这些列按字母顺序插入DF的末尾。

当你想直接对返回的数据帧执行一系列链式操作时,这比简单的赋值更有优势。

考虑@DSM演示的相同DF示例:

df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]})
df
Out[18]:
   A  B
0  1  2
1  2  3
2  3  4

df.assign(C="",D=np.nan)
Out[21]:
   A  B C   D
0  1  2   NaN
1  2  3   NaN
2  3  4   NaN

请注意,这将返回一个副本,其中包含所有以前的列以及新创建的列。为了对原始DF进行相应的修改,可以这样使用:DF = DF .assign(…),因为它目前不支持就地操作。

可以用df。插入(index_to_insert_at, column_header, init_value)在特定索引处插入新列。

cost_tbl.insert(1, "col_name", "") 

上面的语句将在第一列之后插入一个空列。

@emunsing的回答非常酷,可以添加多列,但我在python 2.7中无法让它为我工作。相反,我发现这个方法很有效:

mydf = mydf.reindex(columns = np.append( mydf.columns.values, ['newcol1','newcol2'])