9

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

Vincent
  • 1,534
  • 3
  • 20
  • 42
  • 1
    Possible duplicate of [Pandas: Add multiple empty columns to DataFrame](https://stackoverflow.com/questions/30926670/pandas-add-multiple-empty-columns-to-dataframe) – Fabian Ying Jul 24 '18 at 10:05
  • As I see so many answers to this post. I suggest op to go to this link http://pbpython.com/pandas-list-dict.html to get a clear picture of how it works – Raghav Patnecha Jul 24 '18 at 10:17

6 Answers6

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.

Fabian Ying
  • 1,216
  • 1
  • 10
  • 15
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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
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 ?

Rabin Lama Dong
  • 2,422
  • 1
  • 27
  • 33
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)
FLab
  • 7,136
  • 5
  • 36
  • 69
0

Try looping through the column names before creating the column:

for col in new_cols:
    df[col] = 0
Nordle
  • 2,915
  • 3
  • 16
  • 34
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])
Praveenrajan27
  • 611
  • 6
  • 9