I would like to calculate how many last and previous rows contain value lower than current value - while iterating over dataframe - but the iterator over dataframe is not necessary. Example graphical interpretation:
I used solution from: pandas - Count streak of values higher/lower than current rows, but the result is different than mine.
My code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
df_old = pd.DataFrame({'Spam': [10, 1, 2, 3, 4, 5, 6, 8, 3, 4, 7, 8, 9, 1, 2, 7, 11]})
print(df_old, "\n")
for i in range(0, len(df_old)):
df = df_old.iloc[0:i+1]
number_of_rows_with_lower_value = 0
for j in range(len(df)):
if (df['Spam'].iloc[-1] > df['Spam'].iloc[-j-1:-1].max()):
number_of_rows_with_lower_value = j
print("At row:", i, "value of Spam=", df['Spam'].iloc[-1], "is higher than in last:", number_of_rows_with_lower_value, "rows!")
Spam = df_old['Spam']
Higher=[(Spam[x]>Spam[:x]).sum() for x in range(len(Spam))]
print(Higher)
It gives output:
At row: 0 value of Spam= 10 is higher than in last: 0 rows!
At row: 1 value of Spam= 1 is higher than in last: 0 rows!
At row: 2 value of Spam= 2 is higher than in last: 1 rows!
At row: 3 value of Spam= 3 is higher than in last: 2 rows!
At row: 4 value of Spam= 4 is higher than in last: 3 rows!
At row: 5 value of Spam= 5 is higher than in last: 4 rows!
At row: 6 value of Spam= 6 is higher than in last: 5 rows!
At row: 7 value of Spam= 8 is higher than in last: 6 rows!
At row: 8 value of Spam= 3 is higher than in last: 0 rows!
At row: 9 value of Spam= 4 is higher than in last: 1 rows!
At row: 10 value of Spam= 7 is higher than in last: 2 rows!
At row: 11 value of Spam= 8 is higher than in last: 3 rows!
At row: 12 value of Spam= 9 is higher than in last: 11 rows!
At row: 13 value of Spam= 1 is higher than in last: 0 rows!
At row: 14 value of Spam= 2 is higher than in last: 1 rows!
At row: 15 value of Spam= 7 is higher than in last: 2 rows!
At row: 16 value of Spam= 11 is higher than in last: 16 rows!
[0, 0, 1, 2, 3, 4, 5, 6, 2, 4, 8, 9, 11, 0, 2, 10, 16]
My approach works as desired, giving good results, but is very slow for larger dataframes. The vectorized solution gives different results than mine, so question is - how can I vectorize the code, i.e. using sums?