Skip to content Skip to sidebar Skip to footer

Condition Function Inclusing A Formula On Counting And Summation Of Values Of Columns In A Dataframe

This post is a continuation on this question here. I have a data frame having three columns named 'Altitude', 'Distance', 'Slope'. The column of 'Slope' should be calculated using

Solution 1:

Going through the changes in calculation for 'Slope' that you mentioned in your previous question, I have modified the code accordingly. Try this one out:

sum_distance = 0
idx = 0
prev_idx = -1
slopes = []

for idx, i in enumerate(df.Distance.values):
    sum_distance += i
    if sum_distance >= 10:
        slopes += [(df.Altitude.iloc[idx] - df.Altitude.iloc[prev_idx + 1]) / sum_distance] * (idx - prev_idx)
        sum_distance = 0
        prev_idx = idx

if idx != prev_idx:
    slopes += [(df.Altitude.iloc[idx] - df.Altitude.iloc[prev_idx + 1]) / sum_distance] * (idx - prev_idx)
    
df['Slope'] = slopes

Output:

>>> df
   Altitude  Distance     Slope
0      11.2     0.000 -0.091127
1      11.2     3.018 -0.091127
2      10.9     4.180 -0.091127
3      10.1     4.873 -0.091127
4       9.9     5.499 -0.043775
5       9.4     5.923 -0.043775
6       9.2     6.415 -0.106045
7       8.5     1.063 -0.106045
8       8.4     1.667 -0.106045
9       7.9     3.114 -0.106045

The code sums 'Distance', and tracks whenever the sum is 10 or more, then calculates Differential 'Altitude' and finally Slope using the formula mentioned.


Post a Comment for "Condition Function Inclusing A Formula On Counting And Summation Of Values Of Columns In A Dataframe"