python - 使用 Pandas 将多个数据框合并为一个

标签 python pandas merge dataframe

我有一个数据框 df:

   fruit      date    volume
0  apple    20141001    2000
1  apple    20141101    1800
2  apple    20141201    2200
3  orange   20141001    1900
4  orange   20141101    2000
5  orange   20141201    3000
….

我有以下两个数据框

苹果:

   date       price
0  20141001   2
1  20141101   2.5
2  20141201   3

橙色:

   date       price
0  20141001   1.5
1  20141101   2
2  20141201   2

如何将所有这些合并到以下数据框中:

   fruit      date    price    volume
0  apple    20141001   2       2000
1  apple    20141101   2.5     1800
2  apple    20141201   3       2200
3  orange   20141001   1.5     1900
4  orange   20141101   2       2000
5  orange   20141201   2       3000
….

这只是一个例子,在我的实际工作中,我有数百个带有价格数据的“水果”需要合并到第一个数据框中。

我应该使用合并还是加入?它们之间有什么区别?谢谢。

最佳答案

对于您的示例数据,您可以通过执行 concat 两次来实现您想要的效果,这假定最后 2 个 dfs 与主 df 对齐。内部 concat 将 2 个补充 df 按行连接成一个 df,外部 concat 按列连接:

In [56]:
# this concats the 2 supplementary dfs row-wise into a single df
pd.concat([df1,df2], ignore_index=True)
Out[56]:
       date  price
0  20141001    2.0
1  20141101    2.5
2  20141201    3.0
3  20141001    1.5
4  20141101    2.0
5  20141201    2.0
In [54]:
# now concat column-wise with the main df
pd.concat([df,pd.concat([df1,df2], ignore_index=True)], axis=1)
Out[54]:
    fruit      date  volume      date  price
0   apple  20141001    2000  20141001    2.0
1   apple  20141101    1800  20141101    2.5
2   apple  20141201    2200  20141201    3.0
3  orange  20141001    1900  20141001    1.5
4  orange  20141101    2000  20141101    2.0
5  orange  20141201    3000  20141201    2.0

但是,对于您的真实数据,您需要为每种水果添加价格列:

In [55]:

df[df['fruit'] == 'apple'].merge(df1, on='date')
Out[55]:
   fruit      date  volume  price
0  apple  20141001    2000    2.0
1  apple  20141101    1800    2.5
2  apple  20141201    2200    3.0

对每个水果重复一遍

解决实际数据问题的一种方法是向每个补充 df 添加一个“水果”列,连接所有这些,然后使用“水果”和“日期”列作为键合并回来:

In [57]:

df1['fruit'] = 'apple'
df2['fruit'] = 'orange'
fruit_df = pd.concat([df1,df2], ignore_index=True)
fruit_df
Out[57]:
       date  price   fruit
0  20141001    2.0   apple
1  20141101    2.5   apple
2  20141201    3.0   apple
3  20141001    1.5  orange
4  20141101    2.0  orange
5  20141201    2.0  orange
In [58]:

df.merge(fruit_df, on=['fruit', 'date'])
Out[58]:
    fruit      date  volume  price
0   apple  20141001    2000    2.0
1   apple  20141101    1800    2.5
2   apple  20141201    2200    3.0
3  orange  20141001    1900    1.5
4  orange  20141101    2000    2.0
5  orange  20141201    3000    2.0

关于python - 使用 Pandas 将多个数据框合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28299875/

相关文章:

python - ValueError:无法将输入数组从形状(150528,1)广播到形状(150528)

python - Pandas 将列表列表转换为列名并附加值

python - Pandas 数据框默认使用 .loc

excel - 从vba中的单元格地址获取Excel合并单元格的值

Python:从网页中抓取视频(在 HTML 中不可见)

类的python模拟默认初始化参数

javascript - 如何使用 html 表单作为输入运行 python 函数?

python - 如何根据条件从数据框中交叉制表列?

mysql - 如何使用替换某些唯一数据来暂时合并 2 个表

sql - 合并数据库结构从一台服务器更改到另一台服务器