根据 pandas 中多个列的条件(最大值)替换列中的值

Replace values in a column based on conditions (Max value) from multiple columns in pandas

我有一个数据集,我已经像这样过滤了

在这个数据框的选择中,我想替换 "max” 和 "critical" 列的值,因为“max”列是错误的,它应该显示来自当天的污染物值('pm10'、'so2'、'co'、'o3'、'no2'),临界栏应显示最大污染物的名称那天

期望的结果是:

tanggal stasiun                         pm10  so2   co  o3  no2 max   critical  categori
3515    2020-12-01  DKI1 (Bunderan HI)  22    17    4   19  8   22    PM10      BAIK
3516    2020-12-02  DKI1 (Bunderan HI)  25    18    4   28  7   28    o3        BAIK
3518    2020-12-04  DKI1 (Bunderan HI)  39    29    8   52  17  52    o3        SEDANG
3520    2020-12-06  DKI1 (Bunderan HI)  31    22    7   30  9   31    pm10      BAIK
3521    2020-12-07  DKI1 (Bunderan HI)  25    22    6   18  9   25    pm10      BAIK

第一个是必需的 select 列用于处理 - 例如按名字和姓氏 DataFrame.loc:

df1 = df.loc[:, 'pm10':'no2']

或删除 max 并获取 DataFrame.select_dtypes 中的数字列:

df1 = df.drop(['max'], axis=1).select_dtypes(np.number)

但因为有非数字列先将它们转换为数字:

#for integers
df1 = df.loc[:, 'pm10':'no2'].astype(int)
#or for numeric if some bad values (strings)
df1 = df.loc[:, 'pm10':'no2'].apply(pd.to_numeric, errors='coerce')

然后赋值maxDataFrame.idxmax:

df['max'] = df1.max(axis=1)
df['critical'] = df1.idxmax(axis=1)

print (df)
         tanggal             stasiun  pm10  so2  co  o3  no2  max critical  \
3515  2020-12-01  DKI1 (Bunderan HI)    22   17   4  19    8   22     pm10   
3516  2020-12-02  DKI1 (Bunderan HI)    25   18   4  28    7   28       o3   
3518  2020-12-04  DKI1 (Bunderan HI)    39   29   8  52   17   52       o3   
3520  2020-12-06  DKI1 (Bunderan HI)    31   22   7  30    9   31     pm10   
3521  2020-12-07  DKI1 (Bunderan HI)    25   22   6  18    9   25     pm10   

     categori  
3515     BAIK  
3516     BAIK  
3518   SEDANG  
3520     BAIK  
3521     BAIK