如何在一次分配中向 Pandas 数据框添加多列? [英] How to add multiple columns to pandas dataframe in one assignment?
问题描述
我是 Pandas 的新手,并试图弄清楚如何同时向 Pandas 添加多个列.任何帮助在这里表示赞赏.理想情况下,我希望在一个步骤中完成此操作,而不是多个重复步骤...
I'm new to pandas and trying to figure out how to add multiple columns to pandas simultaneously. Any help here is appreciated. Ideally I would like to do this in one step rather than multiple repeated steps...
import pandas as pd
df = {'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]}
df = pd.DataFrame(df)
df[[ 'column_new_1', 'column_new_2','column_new_3']] = [np.nan, 'dogs',3] #thought this would work here...
推荐答案
我希望你的语法也能正常工作.问题出现是因为当您使用列列表语法 (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]
2) DataFrame
方便地扩展单行以匹配索引,因此您可以这样做:
2) 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)
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
(可能效率较低):
4) Similar to the previous, but using 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']
))
5) 与前两种相比,使用 dict 是一种更自然"的方式来创建新数据框,但新列将按字母顺序排序(至少 Python 3.6 或 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 的早期版本中是这样:
6) Use .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)
7) 这很有趣(基于 https://stackoverflow.com/a/44951376/3830997),但我不知道什么时候值得麻烦:
7) This is interesting (based on https://stackoverflow.com/a/44951376/3830997), but I don't know when it would be worth the trouble:
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
注意:其他答案中已经涵盖了其中的许多选项:将多个列添加到 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
这篇关于如何在一次分配中向 Pandas 数据框添加多列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!