我本来希望你的语法也能工作。出现问题是因为当您使用列列表语法 (df[[new1, new2]] = ...) 创建新列时,pandas 要求右侧是 DataFrame(请注意,DataFrame 的列是否具有相同的名称实际上并不重要作为您正在创建的列)。
您的语法适用于将标量值分配给现有列,pandas 也很乐意使用单列语法 (df[new1] = ...) 将标量值分配给新列。所以解决办法是要么把它转换成几个单列赋值,要么为右边创建一个合适的DataFrame。
以下是几种将起作用的方法:
import pandas as pd
import numpy as np
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
然后是以下之一:
1) 三赋值合一,使用列表解包:
df['column_new_1'], df['column_new_2'], df['column_new_3'] = [np.nan, 'dogs', 3]
2) DataFrame 方便地扩展单行以匹配索引,因此您可以这样做:
df[['column_new_1', 'column_new_2', 'column_new_3']] = pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index)
3) 用新列制作一个临时数据框,稍后再与原始数据框合并:
df = pd.concat(
[
df,
pd.DataFrame(
[[np.nan, 'dogs', 3]],
index=df.index,
columns=['column_new_1', 'column_new_2', 'column_new_3']
)
], axis=1
)
4) 与上一个类似,但使用join 而不是concat(可能效率较低):
df = df.join(pd.DataFrame(
[[np.nan, 'dogs', 3]],
index=df.index,
columns=['column_new_1', 'column_new_2', 'column_new_3']
))
5) 使用 dict 是一种比前两种更“自然”的方式来创建新数据框,但新列将按字母顺序排序(至少 before Python 3.6 or 3.7):
df = df.join(pd.DataFrame(
{
'column_new_1': np.nan,
'column_new_2': 'dogs',
'column_new_3': 3
}, index=df.index
))
6) 将.assign() 与多个列参数一起使用。
我非常喜欢@zero 的答案中的这个变体,但与上一个一样,新列将始终按字母顺序排序,至少对于早期版本的 Python:
df = df.assign(column_new_1=np.nan, column_new_2='dogs', column_new_3=3)
new_cols = ['column_new_1', 'column_new_2', 'column_new_3']
new_vals = [np.nan, 'dogs', 3]
df = df.reindex(columns=df.columns.tolist() + new_cols) # add empty cols
df[new_cols] = new_vals # multi-column assignment works for existing cols
8) 最后很难击败三个独立的任务:
df['column_new_1'] = np.nan
df['column_new_2'] = 'dogs'
df['column_new_3'] = 3
注意:其中许多选项已包含在其他答案中:Add multiple columns to DataFrame and set them equal to an existing column、Is it possible to add several columns at once to a pandas DataFrame?、Add multiple empty columns to pandas DataFrame