Pandas Python : how to create multiple columns from a list

时间:2018-07-24 10:01:19

标签: python pandas dataframe

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 : Pandas: Add multiple empty columns to 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

6 个答案:

答案 0 :(得分:1)

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.

答案 1 :(得分:0)

Try looping through the column names before creating the column:

for col in new_cols:
    df[col] = 0

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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)

答案 4 :(得分:0)

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 ?

答案 5 :(得分:0)

我们可以使用Apply函数遍历数据框中的列,并将每个元素分配给一个新字段 例如,数据框中的列表具有名为keys的列表

[10,20,30]

在您的情况下,由于其全为0,因此我们可以直接将它们指定为0,而无需循环通过。但是,如果我们有值,我们可以如下填充它们 ...

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