How to add an empty column to a dataframe?

后端 未结 11 645
自闭症患者
自闭症患者 2020-11-28 01:06

What\'s the easiest way to add an empty column to a pandas DataFrame object? The best I\'ve stumbled upon is something like

df[\'foo\'] = df.ap         


        
11条回答
  •  长情又很酷
    2020-11-28 01:28

    To add to DSM's answer and building on this associated question, I'd split the approach into two cases:

    • Adding a single column: Just assign empty values to the new columns, e.g. df['C'] = np.nan

    • Adding multiple columns: I'd suggest using the .reindex(columns=[...]) method of pandas to add the new columns to the dataframe's column index. This also works for adding multiple new rows with .reindex(rows=[...]). Note that newer versions of Pandas (v>0.20) allow you to specify an axis keyword rather than explicitly assigning to columns or rows.

    Here is an example adding multiple columns:

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

    or

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

    You can also always concatenate a new (empty) dataframe to the existing dataframe, but that doesn't feel as pythonic to me :)

提交回复
热议问题