根据 Pandas 数据框中其他列的值设置列的值 [英] Setting value of a column based on values of other columns in Pandas dataframe
本文介绍了根据 Pandas 数据框中其他列的值设置列的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个 Pandas 数据框:
I have this Pandas dataframe:
这是关于两国间板球比赛的一些虚构数据.我想根据这个简单的逻辑设置列获胜者的值:
This is some fictional data about games of cricket played between two countries. I want to set the value of column winner based on this simple logic:
if country_1_runs == country_2_runs:
winner = 3
elif country_1_runs > country_2_runs:
winner = 1
else:
winner = 2
我了解 Pandas 中的 map 和 apply 方法.但我不确定它们是否允许上述条件表达式.
I know about map and apply methods in Pandas. But I'm not certain if they allow conditional expressions like the above.
推荐答案
使用 numpy.select
:
m1 = df.country_1_runs == df.country_2_runs
m2 = df.country_1_runs > df.country_2_runs
df['winner'] = np.select([m1, m2], [3, 1], default=2)
这篇关于根据 Pandas 数据框中其他列的值设置列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文