Append min value of two columns in pandas data frame

371 views Asked by At

df

Purchase 
1
3
2
5
4   
7 

df2

df2 = pd.DataFrame(columns=['Mean','Median','Max','Col4'])
df2 = df2.append({'Mean': (df['Purchase'].mean()),'Median':df['Purchase'].median(),'Max':(df['Purchase'].max()),'Col4':(df2[['Mean','Median']].min(axis=1))}, ignore_index=True)

Output obtained

  Mean    Median   Max         Col4
  3.66     3.5      7   Series([], dtype: float64)

Output expected

  Mean    Median   Max         Col4
  3.66     3.5      7           3.5     #Value in Col4 is Min(Mean, Median of df2)

Can anyone help?

1

There are 1 answers

3
jezrael On BEST ANSWER

Use np.minimum and passed mean with median:

df2 = pd.DataFrame(columns=['Mean','Median','Max','Col4'])
df2 = (df2.append({'Mean': df['Purchase'].mean(),
                  'Median':df['Purchase'].median(),
                  'Max':   df['Purchase'].max(),
                  'Col4': np.minimum(df['Purchase'].mean(), df['Purchase'].median())},
                   ignore_index=True))
print (df2)
       Mean  Median  Max  Col4
0  3.666667     3.5  7.0   3.5

Or better is use Series.agg with new value of min in next step, last create one row DataFrame:

s = df['Purchase'].agg(['mean','median','max'])
s.loc['col4'] = s[['mean','median']].min()

df = s.to_frame(0).T
print (df)
       mean  median  max  col4
0  3.666667     3.5  7.0   3.5