如何在pandas中从一个数据框架向另一个数据框架添加列

502 阅读2分钟

你可以使用以下两种方法中的一种,将一列从一个pandas DataFrame添加到另一个DataFrame。

方法1:从一个数据框架添加列到另一个数据框架的最后一列位置

#add some_col from df2 to last column position in df1
df1['some_col']= df2['some_col']

方法2:从一个数据框架中添加列到另一个数据框架中的特定位置

#insert some_col from df2 into third column position in df1
df1.insert(2, 'some_col', df2['some_col'])

下面的例子展示了如何在以下pandas数据框架中实际使用每种方法:

import pandas as pd

#create first DataFrame
df1 = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B'],
                    'position': ['G', 'G', 'F', 'C', 'G', 'C'],
                    'points': [4, 4, 6, 8, 9, 5]})

#view DataFrame
print(df1)

  team position  points
0    A        G       4
1    A        G       4
2    A        F       6
3    A        C       8
4    B        G       9
5    B        C       5

#create second DataFrame
df2 = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B'],
                    'rebounds': [12, 7, 8, 8, 5, 11]})

#view DataFrame
print(df2)

  team  rebounds
0    A        12
1    A         7
2    A         8
3    A         8
4    B         5
5    B        11

例子1:从一个数据框架中添加列到另一个数据框架中的最后一列位置

下面的代码显示了如何将第二个数据框架中的篮板球列添加到第一个数据框架的最后一列位置:

#add rebounds column from df2 to df1
df1['rebounds']= df2['rebounds']

#view updated DataFrame
print(df1)

  team position  points  rebounds
0    A        G       4        12
1    A        G       4         7
2    A        F       6         8
3    A        C       8         8
4    B        G       9         5
5    B        C       5        11

请注意,第二个数据框架中的反弹列已经被添加到第一个数据框架的最后一列位置。

例2:将一个数据框架中的列添加到另一个数据框架中的特定列位置

下面的代码显示了如何将第二个数据框中的篮板列添加到第一个数据框的第三列位置:

#insert rebounds column from df2 into third column position of df1
df1.insert(2, 'rebounds', df2['rebounds'])

#view updated DataFrame
print(df1)

  team position  rebounds  points
0    A        G        12       4
1    A        G         7       4
2    A        F         8       6
3    A        C         8       8
4    B        G         5       9
5    B        C        11       5

请注意,第二个数据框架的篮板列已经被添加到第一个数据框架的第三列位置。

其他资源

下面的教程解释了如何在pandas中执行其他常见任务:

如何在Pandas中改变列的顺序
如何在Pandas中重命名列
如何在Pandas中按名称排序列