Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Python : how to create multiple columns from a list

I have a list with columns to create :

new_cols = ['new_1', 'new_2', 'new_3']

I want to create these columns in a dataframe and fill them with zero :

df[new_cols] = 0

Get error :

"['new_1', 'new_2', 'new_3'] not in index"

which is true but unfortunate as I want to create them...

EDIT : This is a duplicate of this question : Add multiple empty columns to pandas DataFrame however I keep this one too because the accepted answer here was the simple solution I was looking for, and it was not he accepted answer out there

EDIT 2 : While the accepted answer is the most simple, interesting one-liner solutions were posted below

like image 325
Vincent Avatar asked Jul 24 '18 10:07

Vincent


3 Answers

You need to add the columns one by one.

for col in new_cols:
    df[col] = 0

Also see the answers in here for other methods.

like image 83
Fabian Ying Avatar answered Nov 14 '22 22:11

Fabian Ying


Use assign by dictionary:

df = pd.DataFrame({
    'A': ['a','a','a','a','b','b','b','c','d'],
    'B': list(range(9))
})
print (df)
0  a  0
1  a  1
2  a  2
3  a  3
4  b  4
5  b  5
6  b  6
7  c  7
8  d  8

new_cols = ['new_1', 'new_2', 'new_3']
df = df.assign(**dict.fromkeys(new_cols, 0))
print (df)
   A  B  new_1  new_2  new_3
0  a  0      0      0      0
1  a  1      0      0      0
2  a  2      0      0      0
3  a  3      0      0      0
4  b  4      0      0      0
5  b  5      0      0      0
6  b  6      0      0      0
7  c  7      0      0      0
8  d  8      0      0      0
like image 20
jezrael Avatar answered Nov 15 '22 00:11

jezrael


import pandas as pd

new_cols = ['new_1', 'new_2', 'new_3']
df = pd.DataFrame.from_records([(0, 0, 0)], columns=new_cols)

Is this what you're looking for ?

like image 20
Rabin Lama Dong Avatar answered Nov 14 '22 22:11

Rabin Lama Dong