获取 pandas 数据框中最大条目的行和列名称(argmax)

kus*_*ush 5 python numpy feature-selection pandas

df.idxmax() 返回沿轴(行或列)的最大值,但我希望 arg_max(df) 在整个数据帧上,它返回一个元组(行,列)。

我想到的用例是特征选择,其中我有一个相关矩阵,并且想要“递归”删除具有最高相关性的特征。我对相关矩阵进行预处理以考虑其绝对值并将对角线元素设置为 -1。然后我建议使用rec_drop,它递归地删除具有最高相关性的特征对中的一个(受到截止值:max_allowed_correlation),并返回最终的特征列表。例如:

S = S.abs()
np.fill_diagonal(S.values,-1) # so that max can't be on the diagonal now
S = rec_drop(S,max_allowed_correlation=0.95)

def rec_drop(S, max_allowed_correlation=0.99):
    max_corr = S.max().max()
    if max_corr<max_allowed_correlation: # base case for recursion
         return S.columns.tolist() 
    row,col = arg_max(S)  # row and col are distinct features - max can't be on the diagonal
    S = S.drop(row).drop(row,axis=1) # removing one of the features from S
    return rec_drop(S, max_allowed_correlation)
Run Code Online (Sandbox Code Playgroud)

Ima*_*ngo 4

假设所有 pandas 表都是数字的,您可以做的就是转换为 numpy 解释并从中提取最大位置。但是,numpyargmax适用于扁平化数据,因此您需要解决以下问题:

# Synthetic data
>>> table = pd.DataFrame(np.random.rand(5,3))
>>> table
          0         1         2
0  0.367720  0.235935  0.278112
1  0.645146  0.187421  0.324257
2  0.644926  0.861077  0.460296
3  0.035064  0.369187  0.165278
4  0.270208  0.782411  0.690871

[5 rows x 3 columns
Run Code Online (Sandbox Code Playgroud)

将表转换为 numpy 数据并计算 argmax:

>>> data = table.as_matrix()
>>> amax = data.argmax() # 7 in this case
>>> row, col = (amax//data.shape[1], amax%data.shape[1])
>>> row, col
(2, 1)
Run Code Online (Sandbox Code Playgroud)