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?

0

3 Answers 3

8

I prefer this solution.

 df = df.assign(**{'c': 0, 'd': 0}) 
Sign up to request clarification or add additional context in comments.

Comments

2

i got a solution here.

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

will do the trick.

actually it will be:

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

4 Comments

Should be df.reindex(columns = list('abcd')).fillna(0).
yes..actuall fillna(0) is what i was looking for. thank you
What you currently have will throw an error. Should be: columns = list('abcd') or columns = ['a','b','c','d'] for the columns argument.
The solution from @fleurette is safer (no risk of deleting non-mentioned columns) and faster (as no fillna has to be applied afterwards)
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.