Suppose I have a dataframe like such:
import pandas as pd
import numpy as np
data = [[5123, '2021-01-01 00:00:00', 'cash','sales$', 105],
[5123, '2021-01-01 00:00:00', 'cash','items', 20],
[5123, '2021-01-01 00:00:00', 'card','sales$', 355],
[5123, '2021-01-01 00:00:00', 'card','items', 50],
[5123, '2021-01-02 00:00:00', 'cash','sales$', np.nan],
[5123, '2021-01-02 00:00:00', 'cash','items', np.nan],
[5123, '2021-01-02 00:00:00', 'card','sales$', 170],
[5123, '2021-01-02 00:00:00', 'card','items', 35]]
columns = ['Store', 'Date', 'Payment Method', 'Attribute', 'Value']
df = pd.DataFrame(data = data, columns = columns)
| Store | Date | Payment Method | Attribute | Value |
|---|---|---|---|---|
| 5123 | 2021-01-01 00:00:00 | cash | sales$ | 105 |
| 5123 | 2021-01-01 00:00:00 | cash | items | 20 |
| 5123 | 2021-01-01 00:00:00 | card | sales$ | 355 |
| 5123 | 2021-01-01 00:00:00 | card | items | 50 |
| 5123 | 2021-01-02 00:00:00 | cash | sales$ | NaN |
| 5123 | 2021-01-02 00:00:00 | cash | items | NaN |
| 5123 | 2021-01-02 00:00:00 | card | sales$ | 170 |
| 5123 | 2021-01-02 00:00:00 | card | items | 35 |
I would like to create a new attribute, called "average item price", which is generated by, for each Store/Date/Payment Method, dividing the sales$ by the items (e.g. for store 5123, 2021-01-01, cash, I would like to create a new row with an attribute called "average item price", with a value equal to 5.25).
I realize that I could pivot this data out, and have one column for sales, one column for items, and divide the two columns, then restack, but is there a better way to do this without having to pivot?
| Store | Date | Payment Method | Attribute | Value |
|---|---|---|---|---|
| 5123 | 2021-01-01 00:00:00 | cash | sales$ | 105 |
| 5123 | 2021-01-01 00:00:00 | cash | items | 20 |
| 5123 | 2021-01-01 00:00:00 | cash | average item price | 5.25 |
| 5123 | 2021-01-01 00:00:00 | card | sales$ | 355 |
| 5123 | 2021-01-01 00:00:00 | card | items | 50 |
| 5123 | 2021-01-01 00:00:00 | card | average item price | 7.10 |
| 5123 | 2021-01-02 00:00:00 | cash | sales$ | NaN |
| 5123 | 2021-01-02 00:00:00 | cash | items | NaN |
| 5123 | 2021-01-02 00:00:00 | cash | average item price | NaN |
| 5123 | 2021-01-02 00:00:00 | card | sales$ | 170 |
| 5123 | 2021-01-02 00:00:00 | card | items | 35 |
| 5123 | 2021-01-02 00:00:00 | card | average item price | 4.86 |