简体   繁体   English

具有多列的Pandas Data Frame条件流

[英]Pandas Data Frame conditional flow with multiple columns

I have a data frame as follow: 我有一个数据框如下:

fix = pd.DataFrame()
fix ['Home'] =['A','B','C','D','E']
fix ['Away'] =['F','G','H','I','J']
fix ['GD = -2'] = [0.2,0.3,0.5,0.1,0.6]
fix ['GD = -1'] = [0.25,0.1,0.55,0.35,0.43]
fix ['GD = 0'] = [0.1,0.2,0.23,0.5,0.4]
fix ['GD = 2'] = [0.1,0.5,0.2,0.12,0.18]
fix ['GD = 1'] = [0.24,0.5,0.33,0.31,0.13]

I want to create a new column that contain the winning team based on GD (ie GD +ve means Home will win, GD -Ve means Away will win, GD = 0 means draw. 我想创建一个包含基于GD的获胜团队的新列(即GD + ve表示主场获胜,GD -Ve表示客队获胜,GD = 0表示平局。

so I wrote the following code to workout the new column. 所以我写了下面的代码来锻炼新的专栏。

GDPlus = fix ['GD=1'] or fix['GD=2']
GDMins = fix ['GD= -1'] or fix['GD= -2'] 
fix['Winning_Team'] = np.select([GDPlus,GDMins],[fix.Home,fix.Away],default ='Draw')

It threw me an error as follow: 它使我犯了如下错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Could anyone advise how to do that? 有人可以建议如何做吗?

If want new column by max value: 如果要通过max新列:

#get max values per rows
smax = fix.max(axis=1)

compare by eq (==) and check if at least one True per rows
GDPlus = fix[['GD = 1','GD = 2']].eq(smax, axis=0).any(axis=1)
GDMins = fix[['GD = -1','GD = -2']].eq(smax, axis=0).any(axis=1)

Your solution should be changed by comparing by eq ( == ): 您的解决方案应通过比较eq== )来更改:

GDPlus = fix ['GD = 1'].eq(smax) | fix['GD = 2'].eq(smax)
GDMins = fix ['GD = -1'].eq(smax) | fix['GD = -2'] .eq(smax)

#alternative solution
#GDPlus = (fix['GD = 1'] == smax) | (fix['GD = 2'] == smax)
#GDMins = (fix['GD = -1'] == smax) | (fix['GD = -2'] == smax)

fix['Winning_Team'] = np.select([GDPlus,GDMins],[fix.Home,fix.Away],default ='Draw')
print (fix)
  Home Away  GD = -2  GD = -1  GD = 0  GD = 2  GD = 1 Winning_Team
0    A    F      0.2     0.25    0.10    0.10    0.24            F
1    B    G      0.3     0.10    0.20    0.50    0.50            B
2    C    H      0.5     0.55    0.23    0.20    0.33            H
3    D    I      0.1     0.35    0.50    0.12    0.31         Draw
4    E    J      0.6     0.43    0.40    0.18    0.13            J

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM