是否可以一次向 pandas DataFrame添加几列? [英] Is it possible to add several columns at once to a pandas DataFrame?
问题描述
如果要创建一个包含几列的新DataFrame,可以一次添加所有列-例如,如下所示:
If I want to create a new DataFrame with several columns, I can add all the columns at once -- for example, as follows:
data = {'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]}
df = pd.DataFrame(data)
但是现在假设在更远的地方,我想向此DataFrame添加一组其他列.有没有一种方法可以同时添加它们,如
But now suppose farther down the road I want to add a set of additional columns to this DataFrame. Is there a way to add them all simultaneously, as in
additional_data = {'col_3': [8, 9, 10, 11],
'col_4': [12, 13, 14, 15]}
#Below is a made-up function of the kind I desire.
df.add_data(additional_data)
我知道我可以这样做:
for key, value in additional_data.iteritems():
df[key] = value
或者这个:
df2 = pd.DataFrame(additional_data, index=df.index)
df = pd.merge(df, df2, on=df.index)
我只是希望有一些清洁的东西.如果我坚持使用这两个选项,那是首选?
I was just hoping for something cleaner. If I'm stuck with these two options, which is preferred?
推荐答案
Pandas具有0.16.0以来,一直为rel ="noreferrer"> assign
方法.您可以在像
Pandas has assign
method since 0.16.0
. You could use it on dataframes like
In [1506]: df1.assign(**df2)
Out[1506]:
col_1 col_2 col_3 col_4
0 0 4 8 12
1 1 5 9 13
2 2 6 10 14
3 3 7 11 15
或者,您可以直接使用字典,例如
or, you could directly use the dictionary like
In [1507]: df1.assign(**additional_data)
Out[1507]:
col_1 col_2 col_3 col_4
0 0 4 8 12
1 1 5 9 13
2 2 6 10 14
3 3 7 11 15
这篇关于是否可以一次向 pandas DataFrame添加几列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!