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

我是新手,也许我的问题很愚蠢,所以我提前道歉。


基本上我有这样的数据,


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 作为输出的最高作用域编号。


我正在尝试循环,但我没有失败。:(你能帮帮我吗?我真的很感激。


茅侃侃
浏览 77回答 1
1回答

幕布斯6054654

对所有列使用数据帧过滤器,按数据帧检查列的顺序并切片,最后使用数据帧.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 Scope0   1     True     True     True    False      True  Scope 301   2     True     True     True    False     False   Scope 32   3     True     True     True    False      True  Scope 303   4     True    False    False    False     False   Scope 1更通用的解决方案是必要的,以避免错误的输出,如果所有值与numpy.where和DataFrame.any测试至少每行一个:FalseTruedf1 = 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 Scope0   1     True     True     True    False      True  Scope 301   2     True     True     True    False     False   Scope 32   3     True     True     True    False      True  Scope 303   4     True    False    False    False     False   Scope 14   5    False    False    False    False     False  no match
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python