python - 用平均值替换每行的最大值

标签 python pandas dataframe

我想用 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)) 

我的数据框:

<表类=“s-表”> <标题> id 功能0 功能1 功能2 功能3 功能4 <正文> 0 0 0 3 1 5 1 4 0 4 0 8 2 1 21 4 0 0 3 0 11 0 0 2

我想要的输出:

<表类=“s-表”> <标题> id 功能0 功能1 功能2 功能3 功能4 <正文> 0 0 0 3 1 2 1 4 0 4 0 3 2 1 5 4 0 0 3 0 3 0 0 2

最佳答案

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/

相关文章:

python - 与组比较值 - pandas

python - 添加字符串时输出中的额外换行符

python - 调用 groupby 并从 pandas 转移时如何保留列顺序?

python - 迭代图中的标记

python - Pandas 的最后值(value)

python - 使用PeriodIndex对pandas系列进行切片

r - 通过自定义行分隔符聚合

python - 如何对Python列表中的列值进行操作

r - 删除数据框中的一行并取回数据框

python - 尝试创建在 6 次错误输入用户名和密码后退出的程序