更新时间:2023-12-01 10:13:40
我希望你的语法也能正常工作.问题出现是因为当您使用列列表语法 (df[[new1, new2]] = ...
) 创建新列时,pandas 要求右侧是一个 DataFrame(注意DataFrame 的列是否与您正在创建的列具有相同的名称实际上并不重要).
I would have expected your syntax to work too. The problem arises because when you create new columns with the column-list syntax (df[[new1, new2]] = ...
), pandas requires that the right hand side be a DataFrame (note that it doesn't actually matter if the columns of the DataFrame have the same names as the columns you are creating).
您的语法适用于将标量值分配给现有列,并且 Pandas 也很乐意使用单列语法将标量值分配给新列 (df[new1] =...
).因此,解决方案要么将其转换为多个单列分配,要么为右侧创建一个合适的 DataFrame.
Your syntax works fine for assigning scalar values to existing columns, and pandas is also happy to assign scalar values to a new column using the single-column syntax (df[new1] = ...
). So the solution is either to convert this into several single-column assignments, or create a suitable DataFrame for the right-hand side.
这里有几种行之有效的方法:
import pandas as pd
import numpy as np
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
然后是以下之一:
df['column_new_1'], df['column_new_2'], df['column_new_3'] = [np.nan, 'dogs', 3]
DataFrame
方便地扩展单行以匹配索引,因此您可以这样做:
DataFrame
conveniently expands a single row to match the index, so you can do this:df[['column_new_1', 'column_new_2', 'column_new_3']] = pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index)
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
)
join
而不是 concat
(可能效率较低):
join
instead of concat
(may be less efficient):df = df.join(pd.DataFrame(
[[np.nan, 'dogs', 3]],
index=df.index,
columns=['column_new_1', 'column_new_2', 'column_new_3']
))
df = df.join(pd.DataFrame(
{
'column_new_1': np.nan,
'column_new_2': 'dogs',
'column_new_3': 3
}, index=df.index
))
.assign()
与多个列参数一起使用.我非常喜欢@zero 的答案中的这个变体,但与前一个一样,新列将始终按字母顺序排序,至少在 Python 的早期版本中是这样:
.assign()
with multiple column arguments.I like this variant on @zero's answer a lot, but like the previous one, the new columns will always be sorted alphabetically, at least with early versions of 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
df['column_new_1'] = np.nan
df['column_new_2'] = 'dogs'
df['column_new_3'] = 3
注意:其他答案中已经涵盖了其中的许多选项:将多个列添加到 DataFrame 并将它们设置为等于现有列, 是否可以一次向 Pandas DataFrame 添加多列?, 将多个空列添加到pandas DataFrame
Note: many of these options have already been covered in other answers: 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