Skip to content Skip to sidebar Skip to footer

Python/ Pandas: Calculate 1. Minimum, 2. Max Of Columns To Left Of Minimum And 3. Max Of Columns To Right Of Minimum

This is a continuation of Python/ Pandas: Finding a left and right max I have a dataframe, with timelines of data. Here is an example: idx Q12000 Q22000 Q32000 Q4200

Solution 1:

You can use .iloc[:1,:] to only select after the first column, and use a bunch of pandas methods like .min, .max, idxmin, idxmax and others:

df['nadir'] = df.iloc[:,1:].min(axis=1)
df['nadir_qtr'] = df.iloc[:,1:].idxmin(axis=1).apply(lambda x: df.columns.get_loc(x))
df['new'] = [df.iloc[i].values for i in df.index]
df['pre_peak'] = df.apply(lambda x: max(x['new'][0:x['nadir_qtr']]), axis=1)
df['post_peak'] = df.apply(lambda x: max(x['new'][x['nadir_qtr']:]), axis=1)
df['pre_peak_qtr'] = pd.Series([s[i] for i, s in zip(df.index, df['pre_peak'].apply(
    lambda x: [i for i in (df.iloc[:,0:-6] == x)
               .idxmax(axis=1)]))]).apply(lambda x: df.columns.get_loc(x))
df['post_peak_qtr'] = pd.Series([s[i] for i, s in zip(df.index, df['post_peak'].apply(
    lambda x: [i for i in (df.iloc[:,0:-6] == x)
               .idxmax(axis=1)]))]).apply(lambda x: df.columns.get_loc(x))
df_new = df[['nadir', 'nadir_qtr', 'pre_peak', 'pre_peak_qtr', 'post_peak', 'post_peak_qtr']]
df_new
Out[1]: 
         nadir  nadir_qtr   pre_peak  pre_peak_qtr  post_peak  post_peak_qtr
idx                                                                         
0    4039370.0          7  4114911.0             1  4254681.0             11
1      21566.0          1    21226.0             0    23232.0              5
2      95958.0          7   103054.0             5   123064.0              9
3      22080.0         11    24186.0             2    22080.0             11
4       6722.0          7     7906.0             1     8326.0             11

Post a Comment for "Python/ Pandas: Calculate 1. Minimum, 2. Max Of Columns To Left Of Minimum And 3. Max Of Columns To Right Of Minimum"