DF 1
| ColA | Colb | Stock | Date |
| -------- | -------------- | -------- | ---------- |
| A | 1 | 3 | 2022-26-12 |
| B | 2 | 3 | 2022-26-12 |
| C | 3 | 3 | 2022-26-12 |
DF 2
| ColA | Colb | Sales | Date |
| -------- | -------------- | -------- | ---------- |
| A | 1 | 1 | 2022-26-12 |
| B | 2 | 1 | 2022-26-12 |
| C | 3 | 1 | 2022-26-12 |
Given any number of columns to join on, how do you do Dataframe arithmetic in pandas, for instance if I wanted to subtract the above two Dataframes to get something like this
STOCK AT END OF THE DAY
| ColA | Colb | Stock | Date |
| -------- | -------------- | -------- | ---------- |
| A | 1 | 2 | 2022-26-12 |
| B | 2 | 2 | 2022-26-12 |
| C | 3 | 2 | 2022-26-12 |
So stock - sales given all the common columns, in this case
Edit: (Since I was told off) The SQL equivalent of what I want in this case would like this if my SQL is correct:
SELECT
DF1.ColA,
DF1.Colb,
DF1.Date,
DF1.Stock - coalesce(DF2.Sales, 0)
FROM
DF1
LEFT JOIN DF2
on
DF1.ColA = DF2.ColA and
DF1.Colb = DF2.Colb and
DF1.Date = DF2.Date
If they have the same number of rows and columns then do something like that:
df3 = df1[['ColA', 'Colb','Date']]
df3['Stock'] = df1.Stock - df2.Sales
However, if they are different merge them then do what you want:
df3= pd.merge(df1, df2, on='ColA', how='inner')
df3['Stock'] = df3.Stock - df3.Sales
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.