Python Forum
Selecting first and last row in python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Selecting first and last row in python
#1
Hi All,

Im trying to compare first and last value in pandas dataframe. My requirement is
if first value of column(id) group by city = last value of column(id) group by city, then create new field NEW and assign value as 1

ex: id city population
1234 chennai 2000
1234 hyd 3000
2345 calcutta 4000
4567 mumbai 5000

ouput should be:

id city population new
1234 chennai 2000 0
1234 hyd 3000 0
2345 calcutta 4000 1
4567 mumbai 5000 1

Please suggest the code in python.
Reply
#2
what have you tried, show code
Reply
#3
My code:

def test(x):
    if((df.groupby(['city']).first())== (df.groupby(['city']).last())):
        df["NEW"]=1
    return x
df
Reply


Forum Jump:

User Panel Messages

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