Calculating difference between first and last line in a dataframe pandas

Asked

Viewed 32 times

0

I have a pandas dataframe with five rows 3 three columns. I want to create a function where my code returns columns where the last row is larger than the first row. In the example of my code I want it to generate me a list with the column name 'Temp01'. I got in the way of creating if/Else to check the columns whose last row is larger than the first. Below follows my code:

#Importa as Bibliotecas Pandas e Numpy
import pandas as pd

#Cria do Dataframe
df0 = pd.DataFrame({'Temp01':[10,20,30,40,15],'Temp02':[50,60,70,70,45],'Temp03':[80,90,100,100,75]})

#Separa Colunas cuja ultima linha seja maior que a primeira
alta =[]#Tendência de Alta

for column in df0.columns: 
  if df0.column[-1]> df0.column[0]:
    text = column
    alta.append(text)
  else:
    pass
print(alta)

1 answer

0


If you don’t have Nan as the first or last element, follow the Low steps

Creating dataframe

df0 = pd.DataFrame({'Temp01':[10,20,30,40,15],'Temp02':[50,60,70,70,45],'Temp03':[80,90,100,100,75]})

print(df0)
   Temp01  Temp02  Temp03
0      10      50      80
1      20      60      90
2      30      70     100
3      40      70     100
4      15      45      75

First element

first = df0.loc[df0.first_valid_index()]

print(first)
Temp01    10
Temp02    50
Temp03    80
Name: 0, dtype: int64

Latest elements

last = df0.loc[df0.last_valid_index()]

print(last)
Temp01    15
Temp02    45
Temp03    75
Name: 4, dtype: int64

Results

print(last - first)
Temp01    5
Temp02   -5
Temp03   -5
dtype: int64


resultados = list(last - first)

print(resultados)
[5, -5, -5]
  • Oops. Thanks for your help. But the result returned me the difference...but I want him to return me the columns ("Temp0", "Temp1", "Temp2") whose last row is greater q the first. But your code has helped me enough. Thank you.

  • 1

    Oops! good that helped. I got caught by the post title "Calculating difference between first and last line on a dataframe pandas"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.