简体   繁体   中英

pandas group and count

I need help with assigning date index (DayCount) and adding an alternate naming column (Alias). I have something like this:
df

ID Date Name

111 1/1/17 Abc

111 1/3/17 xyz

111 1/2/17 ADC

222 1/5/17 ABC

222 1/6/17 XYZ

333 1/10/17 ijk

Ideal result would be:

ID Date DateCount Name Alias

111 1/1/17 1 Abc Adam

111 1/3/17 3 xyz X

111 1/2/17 2 ADC Adam

222 1/5/17 1 ABC Adam

222 1/6/17 2 XYZ X

333 1/10/17 1 ijk Others

For the DateCount column, I know I have to group ID and sort the date but I'm not sure how to assign the index. As for the Alias column, I'm wondering there's a way to assign value by grouping.

Thanks!

IIUC....

d={'X':'X','A':'Adam'}

df['Datecount']=df.sort_values('Date').groupby('ID').cumcount().add(1)
df
Out[324]: 
    ID       Date Name  Datecount
0  111 2017-01-01  Abc          1
1  111 2017-01-03  xyz          3
2  111 2017-01-02  ADC          2
3  222 2017-01-05  ABC          1
4  222 2017-01-06  XYZ          2
5  333 2017-01-10  ijk          1

df['Alias']=df.Name.str[0].str.upper().map(d).fillna('Other')
df
Out[329]: 
    ID       Date Name  Datecount  Alias
0  111 2017-01-01  Abc          1   Adam
1  111 2017-01-03  xyz          3      X
2  111 2017-01-02  ADC          2   Adam
3  222 2017-01-05  ABC          1   Adam
4  222 2017-01-06  XYZ          2      X
5  333 2017-01-10  ijk          1  Other
pd.DataFrame({'ID': [111,111,111], 'Date': ['2007-01-01', '2017-01-03', '2007-01-02'],'Name':['Abc','xyz','rst']})
    Date         ID  Name
 0  2007-01-01  111  Abc
 1  2017-01-03  111  xyz
 2  2007-01-02  111  rst

idx = 1
cols = [1,1,1]
idx2 = 4
colAlias = ['Adam','x','Adam']
df.insert(loc=1, column='DateCount', value=cols)
df.insert(loc=4, column='Alias', value=colAlias)

       Date  DateCount  ID  Name  Alias
0  2007-01-01   1       111  Abc     x
1  2017-01-03   1       111  xyz  Adam
2  2007-01-02   1       111  rst  Adam

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