10

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

2

6 Answers 6

7

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.

Sign up to request clarification or add additional context in comments.

Comments

7

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

Comments

5
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 ?

Comments

1

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)

Comments

0

Try looping through the column names before creating the column:

for col in new_cols:
    df[col] = 0

Comments

0

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.