
[英]Find 5 consecutive row values in Pandas Dataframe that are equal
[英](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.