【发布时间】: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