2017-07-30 37 views
0

另一个专栏中,我有一个数据帧共同值除以2点的值在数据帧的一列,提供它的片断:基于Python中

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 

我想创建一年明智双赢的列表/损失率。我知道如何使用字典和循环来做到这一点。 但是最好的办法是什么。

回答

2

这里有两个选项:

选项1pivot + division,使用pivotwontielost创建单独的列,然后由lost列划分won柱:

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 

选项2groupby + agg,组数据帧由Year,每年dividewon的计数值由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