我基于熊猫DataFrame df
进行了排名,可以在rank_df
中看到。
现在,我想创建一个新的DataFrame results
,它由三列["first", "second", "third"]
组成。此DataFrame应该用rank_df
的相应列名称填充。例如,results
的第一行可能包含['ticker_3', 'ticker_1', 'ticker_4']
。换句话说,first
的列results
应始终包含具有最高排名的rank_df列名。等等...
import numpy as np
import pandas as pd
np.random.seed(123)
cols = ["ticker_" + str(i + 1) for i in range(5)]
df = pd.DataFrame(np.random.rand(3, 5), columns=cols)
df
输出:
ticker_1 ticker_2 ticker_3 ticker_4 ticker_5
0 0.696469 0.286139 0.226851 0.551315 0.719469
1 0.423106 0.980764 0.684830 0.480932 0.392118
2 0.343178 0.729050 0.438572 0.059678 0.398044
生成rank_df:
rank_df = df.rank(axis=1, method="first", ascending=False)
rank_df
输出:
ticker_1 ticker_2 ticker_3 ticker_4 ticker_5
0 2.0 4.0 5.0 3.0 1.0
1 4.0 1.0 2.0 3.0 5.0
2 4.0 1.0 2.0 5.0 3.0
需要产生结果,
# NaNs in this final DataFrame needs to be filled with the respective column names
results = pd.DataFrame(None, index=rank_df.index, columns=["first", "second", "third"])
python大神给出的解决方案
IIUC,您可以尝试使用argsort
:
print(df)
ticker_1 ticker_2 ticker_3 ticker_4 ticker_5
0 0.548814 0.715189 0.602763 0.544883 0.423655
1 0.645894 0.437587 0.891773 0.963663 0.383442
2 0.791725 0.528895 0.568045 0.925597 0.071036
results[:] = df.columns.to_numpy()[np.argsort(-df)][:,:3] #change 3 to n as reqd
print(results)
first second third
0 ticker_2 ticker_3 ticker_1
1 ticker_4 ticker_3 ticker_1
2 ticker_4 ticker_1 ticker_3
用大写字母拆分字符串,但忽略AAA Python Regex - python我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
子条件的python条件覆盖 - python我试图找到一个python代码覆盖率工具,该工具可以衡量语句中是否包含子表达式:例如,我想看看下面的示例是否涵盖了condition1 / condition2 / condtion3?if condition1 or condition2 or condition3: x = true_value python大神给出的解决方案 对此的唯一合理答案是:当前…
USB设备发行 - python我目前正在使用PyUSB。由于我不熟悉USB,所以我不知道如何执行以下操作。我已经从Python PyUSB成功连接到我的USB设备硬件。在代码中,我需要重置USB设备硬件。通过向硬件发送命令来完成。现在,在硬件重置后,我想从Python PyUSB释放当前的USB设备。然后,我想在重置后将其重新连接到USB设备硬件。请让我知道,如何释放USB设备连接和接口…
Python-熊猫描述了抛出错误:无法散列的类型“ dict” - python更新:我正在使用“ Socrata开源API”中的一些示例代码。我在代码中注意到以下注释:# First 2000 results, returned as JSON from API / converted to Python # list of dictionaries by sodapy. 我不熟悉JSON。我已经下载了一个数据集,并创建了一个包含大量…
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…