根据Pandas datafram中其他列的值设置列的值

2024-09-29 21:45:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个熊猫数据框:

enter image description here

这是一些关于两国间板球比赛的虚构数据。我想根据这个简单的逻辑设置column winner的值:

if country_1_runs == country_2_runs:
    winner = 3
elif country_1_runs > country_2_runs:
    winner = 1
else:
    winner = 2

我知道地图和熊猫的应用方法。但我不确定他们是否允许像上面这样的条件表达式。在


Tags: 数据方法if地图runscolumn逻辑条件
2条回答

使用^{}

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)

你可以试试

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))

相关问题 更多 >

    热门问题