[英]Python (2.7) - Simple IF THEN logic considering multiple fields
Attempting to perform something I can do in 5 second in Excel in Python and I'm finding myself very frustrated.尝试在 Python 的 Excel 中执行我可以在 5 秒内完成的事情,但我发现自己非常沮丧。
I have data that looks like this:我有这样的数据:
HomeTeam AwayTeam HomeScore AwayScore TotalScore
0 OAK LAC 26 24 50
1 CHI DET 20 13 33
2 CIN BAL 13 49 62
3 CLE BUF 19 16 35
4 NO ATL 9 26 35
I want to create a NEW COLUMN in the data frame called "WINNER".我想在名为“WINNER”的数据框中创建一个新列。 If HomeScore > AwayScore, I want the new column WINNER to equal the HomeTeam value, ELSE, equal the AwayTeam value.如果 HomeScore > AwayScore,我希望新列 WINNER 等于 HomeTeam 值,否则,等于 AwayTeam 值。 For example,WINNER should = OAK on row 0 and CHI on row 1.例如,WINNER 应该 = OAK 在第 0 行,CHI 在第 1 行。
this is what I have attempted so far, but this did not give me the results needed above.这是我到目前为止所尝试的,但这并没有给我上面需要的结果。
I know this is simple!我知道这很简单! Please help请帮忙
#new df
df1 = df[['HomeTeam','AwayTeam','HomeScore','AwayScore','TotalScore']]
df1['winner'] = lambda x : df['HomeTeam'] if (df['HomeScore'] > df['AwayScore']) else df['AwayTeam']
print(df1.head())
Assuming that using numpy is an option you could do something like df['winner'] = np.where(df['HomeScore'] > df['AwayScore'], df['HomeTeam'], df['AwayScore'])
假设使用 numpy 是一个选项,你可以做类似df['winner'] = np.where(df['HomeScore'] > df['AwayScore'], df['HomeTeam'], df['AwayScore'])
You were close.你很接近。 Try this:试试这个:
df['winner'] = df.apply(lambda x : \
x['HomeTeam'] if (x['HomeScore'] > x['AwayScore']) \
else x['AwayTeam'], axis=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.