Bottom Page

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.
Quote
#2
what have you tried, show code
Quote
#3
My code:

def test(x):
    if((df.groupby(['city']).first())== (df.groupby(['city']).last())):
        df["NEW"]=1
    return x
df
Larz60+ wrote Oct-01-2019, 07:14 PM:
Please post all code, output and errors (in it's entirety) between their respective tags. I did it for you this time, Here are instructions on how to do it yourself next time.
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)