Vincent
Vincent

Reputation: 1604

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

Upvotes: 10

Views: 46504

Answers (6)

Praveenrajan27
Praveenrajan27

Reputation: 641

We can use the Apply function to loop through the columns in the dataframe and assigning each of the element to a new field for instance for a list in a dataframe with a list named keys

[10,20,30]

In your case since its all 0 we can directly assign them as 0 instead of looping through. But if we have values we can populate them as below ...

df['new_01']=df['keys'].apply(lambda x: x[0])
df['new_02']=df['keys'].apply(lambda x: x[1])
df['new_03']=df['keys'].apply(lambda x: x[2])

Upvotes: 0

Rabin Lama Dong
Rabin Lama Dong

Reputation: 2476

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 ?

Upvotes: 5

FLab
FLab

Reputation: 7466

You can use assign:

new_cols = ['new_1', 'new_2', 'new_3']
values = [0, 0, 0]   # could be anything, also pd.Series

df = df.assign(**dict(zip(new_cols, values)

Upvotes: 1

jezrael
jezrael

Reputation: 862406

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

Upvotes: 7

Nordle
Nordle

Reputation: 3001

Try looping through the column names before creating the column:

for col in new_cols:
    df[col] = 0

Upvotes: 0

Fabian Ying
Fabian Ying

Reputation: 1254

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.

Upvotes: 7

Related Questions