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
343 views
in Technique[技术] by (71.8m points)

How to divide one column by another where one dataframe's column value corresponds to another dataframe's column's value in Python Pandas?

Consider the following data frames in Python Pandas:

DataframeA

ColA ColB ColC
1 dog 439
1 cat 932
1 frog 932
2 dog 2122
2 cat 454
2 frog 773
3 dog 9223
3 cat 3012
3 frog 898
question from:https://stackoverflow.com/questions/65872434/how-to-divide-one-column-by-another-where-one-dataframes-column-value-correspon

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

1 Reply

0 votes
by (71.8m points)

you can use .map

if you have multiple keys to join on then merge would be more useful as demonstrated by @anky

df1['ColF'] = df1['ColC'] / df1['ColA'].map(df2.set_index(['ColD'])['ColE'])

ColA   ColB  ColC       ColF
0     1   dog    439   4.346535
1     1   cat    932   9.227723
2     1  frog    932   9.227723
3     2   dog   2122   6.757962
4     2   cat    454   1.445860
5     2  frog    773   2.461783
6     3   dog   9223  74.379032
7     3   cat   3012  24.290323
8     3  frog    898   7.241935

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

...