【问题标题】:How to show differences from two pandas dataframes of different sizes如何显示两个不同大小的熊猫数据框的差异
【发布时间】:2022-01-07 00:04:50
【问题描述】:

如果我有两个看起来像这样的数据框:

current_month
| Product | Revenue | Expense | Profit | PaymentFrequency | Customer |
| ------- | ------- | ------- | ------ | ---------------- | -------- |
| A       | 100     | 100     | 0      | Monthly          | Cust1    |
| B       | 200     | 150     | 50     | Monthly          | Cust2    |
| C       | 90      | 80      | 10     | Monthly          | Cust3    |

previous_month
| Product | Revenue | Expense | Profit | PaymentFrequency | Customer |
| ------- | ------- | ------- | ------ | ---------------- | -------- |
| A       | 120     | 120     | 0      | Monthly          | Cust1    |
| B       | 250     | 175     | 75     | Monthly          | Cust1    |

对于每种产品,我都希望有一个仅包含差异的表格:

Product A
| month | Revenue | Expense |
| ----- | ------- | ------- |
| current_month | 100 | 100 |
| previous_month | 120 | 120 |

Product B
| month | Revenue | Expense | Profit | Customer |
| ----- | ------- | ------- | ------ | -------- |
| current_month | 200 | 150 | 50 | Cust2 |
| previous_month | 250 | 175 | 75 | Cust1 |

Product C
| month | Revenue | Expense | Profit | PaymentFrequency | Customer |
| ----- | ------- | ------- | ------ | ---------------- | -------- |
| current_month | 90      | 80      | 10     | Monthly          | Cust3    |
| previous_month | NaN | NaN | NaN | NaN | NaN |

我已经能够使用 for 循环和 .loc 来识别差异。但是,我正在努力获得所需的输出。

for product in list(current_month.index):
    for field in list(current_month.columns):
        try:
            if current_month[field].loc[product] != previous_month[field].loc[product]:
                print(f'field: {field}')
                print(f'product: {product}')
                print(f'new value: {current_month[field].loc[product]}')
                print(f'old value: {previous_month[field].loc[product]}') 
        except KeyError:
            print(f'field: {field}')
            print(f'product: {product}')
            print(f'new value: {current_month[field].loc[product]}')
            print(f'NaN')

【问题讨论】:

  • 抱歉,不知道为什么会这样发布表格,它们在草稿模式下看起来很好。

标签: python pandas dataframe dictionary


【解决方案1】:

(i) 首先merge 数据帧和stack 它们;这将创建一个 MultiIndex pd.Series 对象df_m

(ii) 重命名 MultiIndex,按它和unstack 排序。

(iii) 过滤产品(这是 MultiIndex 的第一级),转置数据帧,如果值在两个月内重复,则使用 drop_duplicates

df_m = df1.merge(df2, on='Product', how='outer', suffixes=(' current', ' previous')).set_index('Product').stack()
df_m.index = pd.MultiIndex.from_tuples([(i,)+tuple(j.split()) for i,j in df_m.index])
df_m = df_m.sort_index().unstack()


out = [(df_m[df_m.index.get_level_values(0) == product]
        .T
        .replace(np.nan,'NaN')
        .apply(lambda x: x.drop_duplicates(keep=False), axis=0)
        .dropna(axis=1)
        .replace('NaN',np.nan)) 
       for product in ['A','B','C']]
productA, productB, productC = out

输出:

               A        
         Expense Revenue
current      100     100
previous   120.0   120.0

                B                       
         Customer Expense Profit Revenue
current     Cust2     150     50     200
previous    Cust1   175.0   75.0   250.0

                C                                        
         Customer Expense PaymentFrequency Profit Revenue
current     Cust3    80.0          Monthly   10.0    90.0
previous      NaN     NaN              NaN    NaN     NaN

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-05
    • 2013-11-23
    • 2018-04-18
    • 2022-10-02
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    相关资源
    最近更新 更多