Pandas:获取每行中最小值的列名称,并获取与其余列相比的百分比差异

2024-09-27 02:23:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧:

LF  RF  LR  RR  
11  22  33  44  
23  43  23  12  
33  23  12  43

我想完成的是一个计算(目的是确定每行中哪一列的值最低,并确定与其他cols平均值相比的百分比)。 例如: 识别r1中的最小值,即11和列名称(LF)。其余cols平均值为(22+33+44)/3=33。然后我们计算百分比差11/33=0.333

预期产出:

LF  RF  LR  RR  Min_Col dif(%)
11  22  33  44  LF      0.333
23  43  23  12  RR      0.404
33  23  12  43  LR      0.364

写出方程式的正确方法是:

(min_value)/(sum_rest_of_cols/3)

注意:我需要有一个列来指示每行中哪一列是最低的(这是一个识别问题的程序,因此在错误消息中,我们希望能够告诉用户哪一列是给出问题的列)

编辑:

我的代码(df_inter是我定位的原始df,仅用于获取执行此计算所需的列):

df_exc = df_inter.loc[:,['LF_Strut_Pressure', 'RF_Strut_Pressure', 'LR_Strut_Pressure' ,'RR_Strut_Pressure']]
    df_exc['dif(%)'] = df_exc.min(1) * 3 / (df_exc.sum(1) - df_inter.min(1))
    df_exc['Min_Col'] = df_exc.iloc[:, :-1].idxmin(1)
    print(df_exc)

我的输出:

                            LF_Strut            RF_Strut           LR_Strut            RR_Strut    dif(%)      Min_Col
truck_id                                                                                                         
EX7057             0.000000           0.000000           0.000000           0.000000    0.0000     LF_Strut
EX7105             0.000000           0.000000           0.000000           0.000000    0.0000     LF_Strut
EX7106             0.000000           0.000000           0.000000           0.000000    0.0000     LF_Strut
EX7107             0.000000           0.000000           0.000000           0.000000    0.0000     LF_Strut
TD6510         36588.000000       36587.000       36587.00000       36587.00    0.8204     RF_Strut
TD6511         36986.000000       36989.000       36987.00000       36989.00    0.8220     LF_Strut
TD6512         27704.000000       27705.000       27702.00000       27705.00    0.7757     LR_Strut

问题是:在计算TD6510(36587/((36587+36587+36588)/3))时=0.999999。。不是0.8204。我尝试复制0.8204的来源,但没有成功。谢谢所有人的帮助和支持


Tags: dfrrcolmin平均值exccolsinter
3条回答

将{}和{}与{}和{}一起使用:

final = df.assign(Min_Col=df.idxmin(1),
       Diff=df.min(1).div(df.mask(df.isin(df.min(1))).mean(1)))

print(final)

   LF  RF  LR  RR Min_Col      Diff
0  11  22  33  44      LF  0.333333
1  23  43  23  12      RR  0.404494
2  33  23  12  43      LR  0.363636

首先我们使用idxmin

df['dif(%)']=df.min(1)*3/(df.sum(1)-df.min(1))
df['Min_Col']=df.iloc[:,:-1].idxmin(1)
df
   LF  RF  LR  RR    dif(%) Min_Col
0  11  22  33  44  0.333333      LF
1  23  43  23  12  0.404494      RR
2  33  23  12  43  0.363636      LR

您只需进行常规计算,最小列由idxmin给出

# find the mins in each row
mins = df.min(axis=1)

# compute mean of the other values
other_means = (df.sum(1) - mins).div(df.shape[1]-1)


(mins /other_means)*100

输出:

0    33.333333
1    40.449438
2    36.363636
dtype: float64

相关问题 更多 >

    热门问题