Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

python - Substracting values from two different pandas dataframes based on same row values

I have data of two dataframes First dataframe:

Name    price  date
Apple    25   23-9-2021
Orange   35   23-9-2021
Banana   15   23-9-2021
Gauva    10   23-9-2021
Grapes   5    23-9-2021
Sapota   15   22-9-2021
Papaya   33   21-9-2021
Apple    20   23-9-2021
Orange   30   23-9-2021
Banana   10   23-9-2021
Gauva    10   23-9-2021
Grapes   5    23-9-2021
Apple    15   23-9-2021
Orange   25   23-9-2021
Banana   25   23-9-2021
Gauva    20   23-9-2021
Grapes   15    23-9-2021

Second dataframe:

Name   price   date
Apple   80     23-9-2021
Orange  100     23-9-2021
Banana  90     23-9-2021
Gauva   60     23-9-2021
Grapes  45     23-9-2021

In first dataframe sum all price values of same fruit name and do substraction i.e., I want to substract price value of two dataframes based on row values of same Name and Date and store it into first dataframe

Output: first dataframe

Name   price   date
Apple   25     23-9-2021
Orange  35     23-9-2021
Banana  15     23-9-2021
Gauva   10     23-9-2021
Grapes  5      23-9-2021
Sapota  15     22-9-2021
Papaya  33     21-9-2021
Apple    20   23-9-2021
Orange   30   23-9-2021
Banana   10   23-9-2021
Gauva    10   23-9-2021
Grapes   5    23-9-2021
Apple    15   23-9-2021
Orange   25   23-9-2021
Banana   25   23-9-2021
Gauva    20   23-9-2021
Grapes   15    23-9-2021
Apple   20     23-9-2021
Orange  10     23-9-2021
Banana  40     23-9-2021
Gauva   20     23-9-2021
Grapes  15     23-9-2021

I have more than hundred of such fruitnames. I don't know how to do this

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. merge both dataframes
  2. Find the difference in price
  3. concat
df3 = df2.merge(df1, how="left", on=["Name", "date"])
df3["price"] = df3["price_x"]-df3["price_y"]

output = pd.concat([df1, df3.drop(["price_x", "price_y"], axis=1)])

>>> output
     Name  price       date
0   Apple     25  23-9-2021
1  Orange     35  23-9-2021
2  Banana     15  23-9-2021
3   Gauva     10  23-9-2021
4  Grapes      5  23-9-2021
5  Sapota     15  22-9-2021
6  Papaya     33  21-9-2021
0   Apple      5  23-9-2021
1  Orange     10  23-9-2021
2  Banana     15  23-9-2021
3   Gauva     10  23-9-2021
4  Grapes     20  23-9-2021

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...