Home > other >  Python Pandas maximum and minimum values of every row if header name contain str
Python Pandas maximum and minimum values of every row if header name contain str

Time:09-03

i have a df like this and i want to get the minium value from every rows only from headers that contain 'ask' and maximum values from every rows if the headers name contains 'bid' in it. :

            symbol  bid_Binance  ask_Binance  bid_Kucoin  ask_Kucoin  bid_Mexc  ask_Mexc        
819       GRINUSDT          NaN          NaN    0.107270    0.108250       NaN       NaN      
424       MITXUSDT          NaN          NaN    0.005252    0.005300  0.009010  0.009860      

expected result:

            symbol  bid_Binance  ask_Binance  bid_Kucoin  ask_Kucoin  bid_Mexc  ask_Mexc        min_ask      max_bid
819       GRINUSDT          NaN          NaN    0.107270    0.108250       NaN       NaN      0.108250       0.107270 
424       MITXUSDT          NaN          NaN    0.005252    0.005300  0.009010  0.009860      0.005300       0.009010  

I have tried this way, it takes the max values and min values of every rows but i don't know how to filter the header name

    df_merged['min_'] = df_merged.min(axis=1)
    df_merged['max_'] = df_merged.max(axis=1)

CodePudding user response:

You can use filter with an anchored regex:

df['min_ask'] = df.filter(regex='^ask').min(1)
df['max_bid'] = df.filter(regex='^bid').max(1)

If you don't want to anchor to the start, you can use like:

df['min_ask'] = df.filter(like='ask').min(1)
df['max_bid'] = df.filter(like='bid').max(1)

output:

       symbol  bid_Binance  ask_Binance  bid_Kucoin  ask_Kucoin  bid_Mexc  ask_Mexc  min_ask  max_bid
819  GRINUSDT          NaN          NaN    0.107270     0.10825       NaN       NaN  0.10825  0.10727
424  MITXUSDT          NaN          NaN    0.005252     0.00530   0.00901   0.00986  0.00530  0.00901

CodePudding user response:

You can create min_ask as follows:

df.loc[:, df.columns.str.contains('ask')].apply(min, axis=1)
  • Related