简体   繁体   中英

Calculate order percentage for each column value in dataframe

My data is like this:

d = {
    'date' : ['2011-01-01', '2011-01-15', '2011-08-14', '2012-01-01', '2012-06-06', '2013-01-01', '2013-02-01','2013-03-01','2013-04-01', '2013-08-25']
    ,'year' : ['2011','2011','2011','2012','2012','2013','2013','2013','2013', '2013']

}

df = pd.DataFrame(d)

df['date'] = pd.to_datetime(df['date'])
df.sort_values('date', inplace= True)

    date    year
0   2011-01-01  2011
1   2011-01-15  2011
2   2011-08-14  2011
3   2012-01-01  2012
4   2012-06-06  2012
5   2013-01-01  2013

How can I create a order percent for each year, where the first occurrence of a year is 0.0 and the last 1.0?

The output needs to be like this:

date            year    percent
0   2011-01-01  2011    0.00
1   2011-01-15  2011    0.50
2   2011-08-14  2011    1.00
3   2012-01-01  2012    0.00
4   2012-06-06  2012    1.00
5   2013-01-01  2013    0.00
6   2013-02-01  2013    0.25
7   2013-03-01  2013    0.50
8   2013-04-01  2013    0.75
9   2013-08-25  2013    1.00

I was able to accomplish this by creating several separate dataframes per year and apply ing a funtion where I divide each index by len(serie) , but this does not seem efficient because of the number of dataframes created.

You'll need to use groupby and compute the (1) cumcount , and (2) size , then divide the two.

grp = df.groupby('year')   
df['percent'] = grp.cumcount() / (grp['year'].transform('size') - 1)
df   

        date  year  percent
0 2011-01-01  2011     0.00
1 2011-01-15  2011     0.50
2 2011-08-14  2011     1.00
3 2012-01-01  2012     0.00
4 2012-06-06  2012     1.00
5 2013-01-01  2013     0.00
6 2013-02-01  2013     0.25
7 2013-03-01  2013     0.50
8 2013-04-01  2013     0.75
9 2013-08-25  2013     1.00

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