为 Pandas 中的多个列赋值

Assign values to multiple columns in Pandas

我遵循简单的 DataFrame - df:

   0
0  1
1  2
2  3

一旦我尝试创建新列并为其分配一些值,如下例所示:

df['col2', 'col3'] = [(2,3), (2,3), (2,3)]

我得到了以下结构

   0 (col2, col3)
0  1    (2, 3)
1  2    (2, 3)
2  3    (2, 3)

不过,我正在寻找一种方法,如下所示:

   0 col2, col3
0  1    2,   3
1  2    2,   3
2  3    2,   3

看起来解决方案很简单:

df['col2'], df['col3'] = zip(*[(2,3), (2,3), (2,3)])

有一个方便的解决方案,可以通过元组列表将多个系列连接到数据框。您可以从元组列表 before assignment:

构建数据框
df = pd.DataFrame({0: [1, 2, 3]})
df[['col2', 'col3']] = pd.DataFrame([(2,3), (2,3), (2,3)])

print(df)

   0  col2  col3
0  1     2     3
1  2     2     3
2  3     2     3

这很方便,例如,当您希望加入任意数量的系列时。

我 运行 在尝试将多个标量值应用于多个新列时遇到了这个问题,但找不到更好的方法。如果我遗漏了一些明显的东西,请告诉我,但是 df[['b','c']] = 0 不起作用。但这是简化的代码:

# Create the "current" dataframe
df = pd.DataFrame({'a':[1,2]})

# List of columns I want to add
col_list = ['b','c']

# Quickly create key : scalar value dictionary
scalar_dict = { c : 0 for c in col_list }

# Create the dataframe for those columns - key here is setting the index = df.index
df[col_list] = pd.DataFrame(scalar_dict, index = df.index)

或者,看起来稍微快一点的是使用.assign():

df = df.assign(**scalar_dict)

或者可以使用assign

df.assign(col2 = 2, col3= 3)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html