1

I have a Pandas dataframe with a single row. I want to simultaneously add a list of columns, called new_cols, and set all of their values to 0.

Is there a straightforward way of doing this?

My attempt:

article_features[new_cols] = 0 but that doesn't work :(

Thanks!

anon_swe
  • 8,021
  • 17
  • 78
  • 129

3 Answers3

2

We can use assign method.

Demo:

In [43]: df
Out[43]:
   a  b  c
0  1  2  3
1  4  5  6

In [44]: new_cols
Out[44]: ['c1', 'c2', 'c3']

Option 1:

In [46]: df = df.assign(**{c:0 for c in new_cols})

In [47]: df
Out[47]:
   a  b  c  c1  c2  c3
0  1  2  3   0   0   0
1  4  5  6   0   0   0

Option 2:

In [106]: df = df.join(pd.DataFrame(0, df.index, new_cols))

In [107]: df
Out[107]:
   a  b  c  c1  c2  c3
0  1  2  3   0   0   0
1  4  5  6   0   0   0

adding string values:

In [49]: df = df.assign(**{c:'0' for c in new_cols})

In [50]: df
Out[50]:
   a  b  c c1 c2 c3
0  1  2  3  0  0  0
1  4  5  6  0  0  0

In [51]: df.dtypes
Out[51]:
a      int64
b      int64
c      int64
c1    object
c2    object
c3    object
dtype: object
MaxU - stop genocide of UA
  • 191,778
  • 30
  • 340
  • 375
2

Using pd.DataFrame.reindex_axis and the fill_value=0 parameter.

df.reindex_axis(df.columns.union(new_cols), axis=1, fill_value=0)

   a  b  c  c1  c2  c3
0  1  2  3   0   0   0
1  4  5  6   0   0   0

Or for strings use fill_value='0'

df.reindex_axis(df.columns.union(new_cols), 1, fill_value='0')

   a  b  c c1 c2 c3
0  1  2  3  0  0  0
1  4  5  6  0  0  0

Setup
I borrowed objects from @MaxU

df = pd.DataFrame({'a': [1, 4], 'b': [2, 5], 'c': [3, 6]})
new_cols = ['c1', 'c2', 'c3']
piRSquared
  • 265,629
  • 48
  • 427
  • 571
0

You can add columns in a loop:

for col in new_cols:
    df[col] = 0
DYZ
  • 51,549
  • 10
  • 60
  • 87