Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add column to pandas without headers

How does one append a column of constant values to a pandas dataframe without headers? I want to append the column at the end.

With headers I can do it this way:

df['new'] = pd.Series([0 for x in range(len(df.index))], index=df.index)
like image 970
Abhishek Bhatia Avatar asked Feb 26 '17 19:02

Abhishek Bhatia


People also ask

How do I add a column to a Pandas DataFrame?

In pandas you can add/append a new column to the existing DataFrame using DataFrame. insert() method, this method updates the existing DataFrame with a new column. DataFrame. assign() is also used to insert a new column however, this method returns a new Dataframe after adding a new column.


1 Answers

Each not empty DataFrame has columns, index and some values.

You can add default column value and create new column filled by scalar:

df[len(df.columns)] = 0

Sample:

df = pd.DataFrame({0:[1,2,3],
                   1:[4,5,6]})

print (df)
   0  1
0  1  4
1  2  5
2  3  6

df[len(df.columns)] = 0
print (df)
   0  1  2
0  1  4  0
1  2  5  0
2  3  6  0

Also for creating new column with name the simpliest is:

df['new'] = 1
like image 55
jezrael Avatar answered Sep 24 '22 00:09

jezrael