MMMMS
MMMMS

Reputation: 2201

min vs max difference in pandas dataframe by column

I have a dataframe like below,

             40    50    60    
Friday     2.68  2.41  2.02  
Monday     4.07  3.74  3.41  
Thursday   4.94  4.57  4.02  
Tuesday    4.82  4.59  3.98  
Wednesday  2.76  2.68  2.37 

I want to subtract max - min value from each values on 40 to 90 and then find the min value of key value(60) from the calculation.

like [{40:[4.94 - 2.68 = 2.26]},{50:[4.59-2.41=2.18]},{60:[4.02-2.02 = 2]}] and finally,

[{40:[2.26]},{50:[2.18]},{60:[2]}]

FinalOutput = 60

Upvotes: 2

Views: 1432

Answers (2)

jezrael
jezrael

Reputation: 863801

For dictionary use dict comprehension:

d = {k:[v] for k, v in df.max().sub(df.min()).items()}
print (d)
{'50': [2.1799999999999997], '40': [2.2600000000000002], '60': [1.9999999999999996]}

For index of minimal value idxmin:

a = df.max().sub(df.min()).idxmin()
print (a)
60

Detail:

print (df.max().sub(df.min()))
40    2.26
50    2.18
60    2.00
dtype: float64

Upvotes: 3

jpp
jpp

Reputation: 164843

In one calculation, you can use numpy.argmin to index df.columns:

A = df.values

res = df.columns[(A.max(0) - A.min(0)).argmin()]  # 60

If you need intermediary values, then you can split apart the calculation. Note the argument 0 for max and min methods ensure that calculations are performed on each column.

Upvotes: 0

Related Questions