7

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)
Community
  • 1
  • 1
Abhishek Bhatia
  • 9,404
  • 26
  • 87
  • 142

1 Answers1

12

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252