7

how can I initialize multiple columns in a single instance in an existing pandas DataFrame object? I can initialize single column at an instance, this way:

df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6]}, dtype='int')
df['c'] = 0

but i cannot do something like:

df[['c','d']] = 0 or
df[['c']['d']] = 0

is there a way i can achieve this?

Siraj S.
  • 3,481
  • 3
  • 34
  • 48

3 Answers3

8

I prefer this solution.

    df = df.assign(**{'c': 0, 'd': 0})
fleurette
  • 171
  • 1
  • 7
2

i got a solution here.

df.reindex(columns = list['cd'])

will do the trick.

actually it will be:

df.reindex(columns = list['abcd'])
Community
  • 1
  • 1
Siraj S.
  • 3,481
  • 3
  • 34
  • 48
  • 1
    Should be `df.reindex(columns = list('abcd')).fillna(0)`. – Abdou Sep 28 '16 at 21:30
  • yes..actuall fillna(0) is what i was looking for. thank you – Siraj S. Sep 28 '16 at 21:33
  • What you currently have will throw an error. Should be: `columns = list('abcd')` or `columns = ['a','b','c','d']` for the `columns` argument. – Abdou Sep 28 '16 at 21:36
  • The solution from @fleurette is safer (no risk of deleting non-mentioned columns) and faster (as no fillna has to be applied afterwards) – M. Beining Mar 05 '20 at 09:05
1

pd.concat

pd.concat([df, pd.DataFrame(0, df.index, list('cd'))], axis=1)

enter image description here


join

df.join(pd.DataFrame(0, df.index, list('cd')))

enter image description here

piRSquared
  • 285,575
  • 57
  • 475
  • 624