Python Forum
Dataframe: comparing value in last row vs the row before last
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dataframe: comparing value in last row vs the row before last
#1
Question 
Is the following a valid code? I am simply trying to compare the contents of the previous row vs the 2nd previous row.

if row['DIRECTION'].shift(1) == row['DIRECTION'].shift(2)
I am getting this error: AttributeError: 'int' object has no attribute 'shift'.
Reply
#2
what does row look like,
it would have to contain a cell named DIRECTION, and expect it's value to be a string.
Really hard to say without seeing the structure of row.

Also, its this a row from csv.DictReader, or from a database table?
Reply
#3
Given that your topic says "Dataframe", I will make the assumption you are using Pandas. You generally don't loop in Pandas, but here is working code that compares 2 rows of the dataframe df

import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv')

for idx in range(10):
    if df.iloc[idx+1]['Population'] < df.iloc[idx]['Population']:
        print(f'Pop of {df.iloc[idx+1]["State"]} is less than {df.iloc[idx]["State"]}')
Output:
Pop of Alaska is less than Alabama Pop of Arkansas is less than Arizona Pop of Colorado is less than California Pop of Connecticut is less than Colorado Pop of Delaware is less than Connecticut Pop of District of Columbia is less than Delaware Pop of Georgia is less than Florida
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Comparing Dataframe to String? RockBlok 2 410 Nov-24-2023, 04:55 PM
Last Post: RockBlok

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020