pythonpandasdataframe

How to add columns to an empty pandas dataframe?


I have an empty dataframe.

df=pd.DataFrame(columns=['a'])

for some reason I want to generate df2, another empty dataframe, with two columns 'a' and 'b'.

If I do

df.columns=df.columns+'b'

it does not work (I get the columns renamed to 'ab') and neither does the following

df.columns=df.columns.tolist()+['b']

How to add a separate column 'b' to df, and df.emtpy keep on being True?

Using .loc is also not possible

   df.loc[:,'b']=None

as it returns

  Cannot set dataframe with no defined index and a scalar

Solution

  • Here are few ways to add an empty column to an empty dataframe:

    df=pd.DataFrame(columns=['a'])
    df['b'] = None
    df = df.assign(c=None)
    df = df.assign(d=df['a'])
    df['e'] = pd.Series(index=df.index)   
    df = pd.concat([df,pd.DataFrame(columns=list('f'))])
    print(df)
    

    Output:

    Empty DataFrame
    Columns: [a, b, c, d, e, f]
    Index: []
    

    I hope it helps.