如果我有这样的数据帧:
id | col1 | col2 | idxmax |
---|---|---|---|
1 | 3.0 | 4.0 | col2 |
2 | 5.0 | 5.0 | tiebreak |
3 | 6.0 | 9.0 | col 2 |
在我的示例数据帧的情况下,我希望根据赢得平局的名称返回col1或col2.不包括行ID.
目前,根据文档,df.idxmax(axis = 1)
函数只返回具有第一个最大值的列的列名.然而,为了确保消除偏见,我想把这变成一个随机的平局休息,但我真的不知道怎么做.
你能帮帮忙吗?
如果我有这样的数据帧:
id | col1 | col2 | idxmax |
---|---|---|---|
1 | 3.0 | 4.0 | col2 |
2 | 5.0 | 5.0 | tiebreak |
3 | 6.0 | 9.0 | col 2 |
在我的示例数据帧的情况下,我希望根据赢得平局的名称返回col1或col2.不包括行ID.
目前,根据文档,df.idxmax(axis = 1)
函数只返回具有第一个最大值的列的列名.然而,为了确保消除偏见,我想把这变成一个随机的平局休息,但我真的不知道怎么做.
你能帮帮忙吗?
我喜欢@Timless的随机抽样方法,问题是它总是对具有相同相等最大值组合的不同行使用相同的平局决胜法.
另一种方法是先收集stack
个数据:
df['idxmax'] = (df
.drop(columns=['id', 'idxmax'], errors='ignore')
.stack()
.sample(frac=1)
.groupby(level=0).idxmax().str[1]
)
或者:
cols = df.columns.difference(['id', 'idxmax'])
m = df[cols].eq(df[cols].max(axis=1), axis=0)
df['idxmax'] = (m[m].stack().reset_index(1)
.groupby(level=0)['level_1'].sample(n=1)
)
输出示例:
id col1 col2 idxmax
0 1 3.0 4.0 col2
1 2 5.0 5.0 col2
2 3 6.0 9.0 col2