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

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

基本上我有这样的数据,

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 |

我想创建一个名为Top Scope的新列,并使用具有True作为输出的最高范围编号。

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

参考方案

对所有列使用DataFrame.filter,通过DataFrame.iloc和切片检查列的顺序,最后使用DataFrame.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

如果所有带有Falsenumpy.whereDataFrame.any值用于测试每行至少一个True,则需要更通用的解决方案来避免错误输出:

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

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

python类变量可以从类方法访问? - python

我离开python已有一段时间了。我很快就违反了我的理解。考虑:class Foo: a = 1 def bar(): print(a) 我希望通过设定规则范围来将a用于该方法:首先是局部的,然后将其括起来,...类Foo创建一个名称空间和一个范围,不是吗? bar创建一个作用域;它不包含在课程范围内吗?在a的范围中没有定义bar,因此我希望它从封闭的范围中…

Python-Excel导出 - python

我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…

Python:传递记录器是个好主意吗? - python

我的Web服务器的API日志如下:started started succeeded failed 那是同时收到的两个请求。很难说哪一个成功或失败。为了彼此分离请求,我为每个请求创建了一个随机数,并将其用作记录器的名称logger = logging.getLogger(random_number) 日志变成[111] started [222] start…

keras中的自定义RMSPE损失函数 - python

我正在尝试在keras中定义我自己的损失函数,即均方根百分比误差。 RMSPE定义为:我已经将损失函数定义为:from keras import backend as K def rmspe(y_true, y_pred): sum = K.sqrt(K.mean(K.square( (y_true - y_pred) / K.clip(K.abs(y_tr…