mardi 17 août 2021

Find Max Gradient by Row in For Loop Pandas

I have a df of 15 x 4 and I'm trying to compute the maximum gradient in a North (N) minus South (S) direction for each row using a "S" and "N" value for each min or max in the rows below. I'm not sure that this is the best pythonic way to do this. My df "ms" looks like this:

   minSlats  minNlats  maxSlats  maxNlats
0   57839.4   54917.0   57962.6   56979.9
0   57763.2   55656.7   58120.0   57766.0
0   57905.2   54968.6   58014.3   57031.6
0   57796.0   54810.2   57969.0   56848.2
0   57820.5   55156.4   58019.5   57273.2
0   57542.7   54330.6   58057.6   56145.1
0   57829.8   54755.4   57978.8   56777.5
0   57796.0   54810.2   57969.0   56848.2
0   57639.4   54286.6   58087.6   56140.1
0   57653.3   56182.7   57996.5   57975.8
0   57665.1   56048.3   58069.7   58031.4
0   57559.9   57121.3   57890.8   58043.0
0   57689.7   55155.5   57959.4   56440.8
0   57649.4   56076.5   58043.0   58037.4
0   57603.9   56290.0   57959.8   57993.9

My loop structure looks like this:

J = len(ms)
grad = pd.DataFrame()
for i in range(J):
    if  ms.maxSlats.iloc[i]  > ms.maxNlats.iloc[i]:
        gr = ( ms.maxSlats.iloc[i] - ms.minNlats.iloc[i] ) * -1
        grad[gr] = [i+1, i]
    elif ms.maxNlats.iloc[i] > ms.maxSlats.iloc[i]:
        gr = ms.maxNlats.iloc[i] - ms.minSlats.iloc[i]
        grad[gr] = [i+1, i]
grad = grad.T # need to transpose        
print(grad)

I obtain the correct answer but I'm wondering if there is a cleaner way to do this to obtain the same answer below:

grad.T Out[317]:

          0   1
-3045.6   1   0
-2463.3   2   1
-3045.7   3   2
-3158.8   8   7
-2863.1   5   4
-3727.0   6   5
-3223.4   7   6
-3801.0   9   8
-1813.8  10   9
-2021.4  11  10
 483.1   12  11
-2803.9  13  12
-1966.5  14  13
 390.0   15  14

thank you,

Aucun commentaire:

Enregistrer un commentaire