如何在一次分配中向 pandas 数据框添加多列? [英] How to add multiple columns to pandas dataframe in one assignment?
问题描述
我是熊猫的新手,试图弄清楚如何同时向熊猫添加多列.在这里的任何帮助表示赞赏.理想情况下,我希望一步一步完成此操作,而不是重复多次...
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.
以下是将起作用的几种方法:
Here are several approaches that will work:
import pandas as pd
import numpy as np
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
然后执行以下操作之一:
Then one of the following:
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比前两个更自然"地创建新数据框,但是新列将按字母顺序排序(至少
5) Using a dict is a more "natural" way to create the new data frame than the previous two, but the new columns will be sorted alphabetically (at least 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:
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并将其设置为等于现有列,是否可以一次向熊猫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屋!
df = df.join(pd.DataFrame(
{
'column_new_1': np.nan,
'column_new_2': 'dogs',
'column_new_3': 3
}, index=df.index
))
.assign()
与多个列参数一起使用..assign()
with multiple column arguments.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