Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add columns to an empty pandas dataframe?

Tags:

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 
like image 309
00__00__00 Avatar asked May 16 '18 13:05

00__00__00


People also ask

How do I add multiple columns to an empty Data frame?

There are multiple ways to add a new empty/blank column (single or multiple columns) to a pandas DataFrame by using assign operator, assign() , insert() and apply() methods. By using these you can add one or multiple empty columns with either NaN , None , Blank or Empty string values to all cells.

How do you add a column to an empty DF?

To add columns using reindex() method, First, get the list of existing columns in the dataframe by using df. columns. tolist() and add the additional columns to the list. The newly added columns will have NaN values by default to denote the missing values.

How do I add to an empty pandas DataFrame?

Append Rows to Empty DataFramepandas. DataFrame. append() function is used to add the rows of other DataFrame to the end of the given DataFrame and return a new DataFrame object.


1 Answers

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.

like image 132
Sumit Jha Avatar answered Oct 11 '22 23:10

Sumit Jha