【问题标题】:Replace values in a column based on conditions (Max value) from multiple columns in pandas根据熊猫中多列的条件(最大值)替换列中的值
【发布时间】:2022-01-23 11:57:39
【问题描述】:

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

在这个数据框的选择中,我想替换 "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

【问题讨论】:

    标签: pandas dataframe replace


    【解决方案1】:

    首先是选择列进行处理 - 例如按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  
    

    【讨论】:

    • 它给出了一个错误attempt to get argmax of an empty sequence
    • @DiazJubairy - 你能把df['critical'] = df1.idxmax(axis=1)改成df['critical'] = df1.dropna(how='all').idxmax(axis=1)
    • @DiazJubairy - 因为似乎有些行只有 NaN,所以该行的解决方案失败。
    • 它有效!谢谢!
    • @DiazJubairy - 当然,添加到答案中。
    猜你喜欢
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 2018-01-10
    • 2019-07-31
    • 2018-04-26
    • 1970-01-01
    • 2020-05-06
    相关资源
    最近更新 更多