为了账号安全,请及时绑定邮箱和手机立即绑定

Python:如何迭代20列并找到顶部列?

Python:如何迭代20列并找到顶部列?

茅侃侃 2022-09-20 15:18:09
我是新手,也许我的问题很愚蠢,所以我提前道歉。基本上我有这样的数据,ID | Scope 1 | Scope 2 | Scope 3 | Scope 4 | ... | Scope 30|   1  | True    |  True   | True    |  False  | ... |   True  |2  | True    |  True   | True    |  False  | ... |   False |3  | True    |  True   | True    |  False  | ... |   True  |4  | True    |  False  | False   |  False  | ... |   False |我想创建一个名为“顶部作用域”的新列,并具有以 True 作为输出的最高作用域编号。我正在尝试循环,但我没有失败。:(你能帮帮我吗?我真的很感激。
查看完整描述

1 回答

?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

对所有列使用数据帧过滤器,按数据帧检查列的顺序并切片,最后使用数据帧.idxmax

df['Top Scope'] = df.filter(like='Scope').idxmax(axis=1)

#seelcting all columns without first with reversed order

#df['Top Scope'] = df.iloc[:, :0:-1].idxmax(axis=1)

print (df)

   ID  Scope 1  Scope 2  Scope 3  Scope 4  Scope 30 Top Scope

0   1     True     True     True    False      True  Scope 30

1   2     True     True     True    False     False   Scope 3

2   3     True     True     True    False      True  Scope 30

3   4     True    False    False    False     False   Scope 1

更通用的解决方案是必要的,以避免错误的输出,如果所有值与numpy.where和DataFrame.any测试至少每行一个:FalseTrue


df1 = df.filter(like='Scope').iloc[:, ::-1]

df['Top Scope'] = np.where(df1.any(axis=1), df1.idxmax(axis=1), 'no match')

print (df)

   ID  Scope 1  Scope 2  Scope 3  Scope 4  Scope 30 Top Scope

0   1     True     True     True    False      True  Scope 30

1   2     True     True     True    False     False   Scope 3

2   3     True     True     True    False      True  Scope 30

3   4     True    False    False    False     False   Scope 1

4   5    False    False    False    False     False  no match


查看完整回答
反对 回复 2022-09-20
  • 1 回答
  • 0 关注
  • 76 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信