[英]Dividing 2 values in a column of dataframe based on common value in another column in python
I have a dataframe, providing snippet of it: 我有一个数据框,提供了它的摘要:
Year Result Count
2000 lost 5
2000 won 16
2001 lost 12
2001 won 22
2002 lost 15
2002 won 15
2003 lost 12
2003 tied 1
2003 won 13
2004 lost 8
2004 won 20
I want to create a list of year wise win/loss ratio. 我想创建一个年度明智的赢/输比率的列表。 I know how to to do it using dictionary and loop.
我知道如何使用字典和循环来做到这一点。 But what is the best way to do it.
但是什么是最好的方法。
Here are two options: 这里有两个选择:
Option 1 : pivot
+ division
, use pivot
to create separate columns for won
, tie
and lost
and then divide the won
column by the lost
column: 选项1 :
pivot
+ division
,使用pivot
为won
, tie
和lost
创建单独的列,然后将won
列除以lost
列:
df.pivot("Year", "Result", "Count").pipe(lambda x: x.won/x.lost)
#Year
#2000 3.200000
#2001 1.833333
#2002 1.000000
#2003 1.083333
#2004 2.500000
#dtype: float64
Option 2 : groupby
+ agg
, group data frame by Year
, and for each year divide
the Count value of won
by lost
: 选项2:
groupby
+ agg
,按组数据帧Year
,每年为divide
的计数值won
由lost
:
df.Count = df.Count.astype(float)
(df.set_index('Result').groupby('Year').Count
.agg(lambda x: x.get('won', np.nan)/x.get('lost', np.nan)))
#Year
#2000 3.200000
#2001 1.833333
#2002 1.000000
#2003 1.083333
#2004 2.500000
#Name: Count, dtype: float64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.