简体   繁体   English

根据python另一列中的公共值在数据框的一列中划分2个值

[英]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: 选项1pivot + division ,使用pivotwontielost创建单独的列,然后将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的计数值wonlost

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.

相关问题 根据 dataframe 中的另一个值划分 dataframe 中的值 - Dividing values in a dataframe based on another value in dataframe 如何根据公共值将数据框中列的值添加到另一个数据框中? 熊猫/蟒蛇 - how to add values of a column in dataframe to another dataframe based on common values? pandas/python 如何使用另一个数据框添加数据框并基于列更新公共值 - how to add a dataframe with another dataframe and updated common values based on a column 如何根据公共列将 dataframe 的列值替换为另一个 dataframe 的值? - How do I replace column values of a dataframe with values of another dataframe based on a common column? 根据另一列查找公共列值 - Find common column values based on another column Python Dataframe:根据另一个数据帧更新数据框中列的值 - Python Dataframe : Update the values of a column in a dataframe based on another dataframe 根据另一列值划分同一列中的行 - Dividing rows in same column based on another column value Python Dataframe:根据另一列更改列的值? - Python Dataframe:Change values of a column based on another column? Python 根据另一个 dataframe 中的列值匹配列名 - Python match a column name based on a column value in another dataframe Python根据存在于另一个数据帧值中的列索引填充数据帧值 - Python Filling dataframe values based on Column Index present in another dataframe value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM