我想用 mean
替换列中每行的最大值该行的值。我正在使用的方法需要花费很多时间才能完成。我正在使用 pandas DataFrame
。替换的平均值需要是整数,但具有正确的洪水划分。 example: if value is 3.2 then 3 or if value is 3.8 then 4.
我的缓慢解决方案:
for j in range(0,len(df_train)):
val = df_train.iloc[j,1:51].mean()
m = df_train.iloc[j,1:51].max()
df_train.iloc[j,1:51] = df_train.iloc[j,1:51].replace(m,int(val))
我的数据框:
我想要的输出:
2
3
5
3
最佳答案
df.values[range(len(df.index)), np.argmax(df.values, axis=1)] = df.mean(axis=1).round()
行上的 np.argmax
告诉我们每行每个最大值的位置。然后,我们对 df.values
使用奇特的索引,并在行 (axis=1
) 上分配 mean
值,但 round
编辑。
获取
feature0 feature1 feature2 feature3 feature4
id
0 0 0 3 1 2
1 4 0 4 0 3
2 1 5 4 0 0
3 0 3 0 0 2
关于python - 用平均值替换每行的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67406374/