Python Forum

Full Version: Selecting first and last row in python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
what have you tried, show code
My code:

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