繁体   English   中英

(Pandas)是否有更快的方法来查找一行中所有值的索引,这些值等于 pandas 中该行中的最大值?

[英](Pandas) Is there a faster way to find the indexes of all values in a row which are equal to the max in that row in pandas?

我有一个带有多列浮点值的 pandas dataframe Cellvoltage。 我正在尝试获取等于每行最大值的所有值的索引。

因此,为了实现这一点,我使用以下代码:

req_indices = np.argwhere(Cellvoltage.values == np.amax(Cellvoltage.values, axis=1).reshape(-1,1))
max_voltage_idx = [0]*len(req_indices)
for x,y in req_indices:
    if max_voltage_idx[x] == 0:
        max_voltage_idx[x] = [y]
    else:
        max_voltage_idx[x].append(y)
Cellvoltage['max_voltage_idx']  = pd.Series(max_voltage_idx).apply(np.array)

是否有更好/更快的方法来实现相同的目标?

df.eq(df.max(axis=1), axis=0)where一起使用以屏蔽非最大值,然后stack以移除 NaN 并获取索引对。

out = df.where(df.eq(df.max(axis=1), axis=0)).stack().index.tolist()

输入示例:


   A  B  C  D
0  1  2  3  3
1  4  1  1  4

Output:

[(0, 'C'), (0, 'D'), (1, 'A'), (1, 'D')]

如果您只想将列表中的列作为新列,请添加groupby.agg步骤:

df['max_voltage_idx']= (df                  
   .where(df.eq(df.max(axis=1), axis=0)).stack()
   .reset_index(-1).iloc[:, 0]
   .groupby(level=0).agg(list)
 )

Output:

   A  B  C  D max_voltage_idx
0  1  2  3  3          [C, D]
1  4  1  1  4          [A, D]

另一种可能的解决方案:

indices = np.where(df.values == np.amax(df.values, axis=1)[:, None])
list(zip(indices[0], df.columns.values[indices[1]]))

Output:

[(0, 'C'), (0, 'D'), (1, 'A'), (1, 'D')]

输入:

同样的@mozway(我感谢他)使用:

   A  B  C  D
0  1  2  3  3
1  4  1  1  4

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM