[英]Setting value of a column based on values of other columns in Pandas dataframe
I have this Pandas dataframe: 我有这个Pandas数据帧:
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
I know about map and apply methods in Pandas. 我知道Pandas中的地图和应用方法。 But I'm not certain if they allow conditional expressions like the above.
但我不确定他们是否允许像上面这样的条件表达式。
Use numpy.select
: 使用
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)
You can try 你可以试试
df['winner'] = np.where(df['country_1_runs'] == df['country_2_runs'], 3,
np.where(df['country_1_runs']> df['country_2_runs'], 1, 2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.