How to add an empty column to a dataframe?

后端 未结 11 660
自闭症患者
自闭症患者 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:39

    The below code address the question "How do I add n number of empty columns to my existing dataframe". In the interest of keeping solutions to similar problems in one place, I am adding it here.

    Approach 1 (to create 64 additional columns with column names from 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
    

    Approach 2 (to create 64 additional columns with column names from 1-64)

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

提交回复
热议问题