简体   繁体   中英

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)
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)
m = (df0.tail(1).values > df0.head(1).values)[0]
print(df0.columns[m].values)

Prints:

['Temp01']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM