Rodrigo Ferraz
Rodrigo Ferraz

Reputation: 127

Selecting a column from a conditional loop on a pandas dataframe

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 greater than the first row. In my code example I want it to generate a list with the column name 'Temp01'. I fumbled when creating the if / else to check the columns whose last row is longer than the first. Below is my code:

#Import pandas package
import pandas as pd

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

#empty list with column names
test =[]

for column in df0.columns: 
#df0.column[-1] - Last row of each dataframe column
#df0.column[0] - First row of each dataframe column

  if df0.column[-1]> df0.column[0]:
    text = column
    test.append(text)
  else:
    pass
print(test)

Upvotes: 0

Views: 219

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195428

m = (df0.tail(1).values > df0.head(1).values)[0]
print(df0.columns[m].values)

Prints:

['Temp01']

Upvotes: 1

aj7amigo
aj7amigo

Reputation: 378

import pandas as pd

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

lst=[]

for col_name in df0.columns:
    if df0[col_name].iloc[-1]>df0[col_name].iloc[0]:
        lst.append(col_name)
print(lst)

Upvotes: 1

Related Questions