If I have two dataframes that look like:
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 |
For each product I would like to have a table of just the differences:
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 |
I've been able to identify the differences using a for loop and .loc. However, I am struggling to get the desired output.
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')