python - pandas 合并两个数据框并汇总单元格值

标签 python pandas dataframe

我尝试按月份列合并2个数据框,并对全价实际价格折扣 行。

示例如下:

# First DataFrame
  month  fullprice  actualprice  discount
0   Jan         10            7         3
1   Feb          6            4         2


# Second DataFrame
  month  fullprice  actualprice  discount
0   Jan         11            5         6
1   Feb          6            4         2
2   Mar        100           50        50


# Desired result
  month  fullprice  actualprice  discount
0   Jan         21            12        9
1   Feb         12             8        4
2   Mar        100            50        50

尝试了几种方法,但这不是我需要的:

df1 = pd.DataFrame([['Jan', 10, 7, 3], ['Feb', 6, 4, 2]], columns=['month', 'fullprice', 'actualprice', 'discount'])
df2 = pd.DataFrame([['Jan', 11, 5, 6], ['Feb', 6, 4, 2], ['Mar', 100, 50, 50]], columns=['month', 'fullprice', 'actualprice', 'discount'])

df2.add(df1)

       month  fullprice  actualprice  discount
    0  JanJan       21.0         12.0       9.0
    1  FebFeb       12.0          8.0       4.0
    2     NaN        NaN          NaN       NaN

df1.merge(df2, how='right')

        month  fullprice  actualprice  discount
    0   Feb          6            4         2
    1   Jan         11            5         6
    2   Mar        100           50        50

df1.merge(df2, on='month', how='right')

        month  fullprice_x  actualprice_x  discount_x  fullprice_y actualprice_y  \
    0   Jan         10.0            7.0         3.0           11              5   
    1   Feb          6.0            4.0         2.0            6              4   
    2   Mar          NaN            NaN         NaN          100             50   

        discount_y  
    0           6  
    1           2  
    2          50

有什么想法如何合并它吗?

最佳答案

使用追加然后分组。

df1 = df1.set_index('month')
df2 = df2.set_index('month')
df1.append(df2).groupby(level=0).sum()

       fullprice  actualprice  discount
month                                  
Feb           12            8         4
Jan           21           12         9
Mar          100           50        50

或者如果没有索引:

df1.append(df2).groupby('month').sum()

关于python - pandas 合并两个数据框并汇总单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42957179/

相关文章:

python - 如何访问 Delicious API 以检索 Google 相关关键字

Python Pandas Dataframe - 基于条件的分组和平均

python - 如何在数据框的某些行的所有列上使用 pandas apply 函数

python - 有没有办法以列表格式填充数据框中的缺失值作为上一行列表的最后一个值?

pandas - 重复将多个 Panda 数据导出到多个 csv 文件的任务

python - 使用 tf.keras.application 时如何获得中间输出

python - 将数据框 reshape 为具有无限行并在没有值的情况下填充零的数据框

python - 如何更干净地分割 Pandas 中的数据?

python - 无法根据python中的用户输入过滤csv表中的数据

python - Pandas 多重索引在给定元组时成功,在给定列表时失败