简体   繁体   中英

Generate numbered rows in indexed Pandas DataFrame

In a DataFrame like this where horse is the index, how can I generate a column where it creates an integer incrementing by one?

Starting DataFrame...

                  line_race  daysago
horse                               
Last Gunfighter          10       35
Last Gunfighter          10       76
Last Gunfighter           8      119
Last Gunfighter          12      169
Last Gunfighter           9      224
Paynter                  10       35
Paynter                  10       63
Paynter                   8       98
Paynter                   7      141

...to this...

                  line_race  daysago    row
horse                               
Last Gunfighter          10       35      1
Last Gunfighter          10       76      2
Last Gunfighter           8      119      3
Last Gunfighter          12      169      4
Last Gunfighter           9      224      5
Paynter                  10       35      1
Paynter                  10       63      2
Paynter                   8       98      3
Paynter                   7      141      4
In [19]: df = DataFrame(np.arange(14).reshape((7,2)),
                        columns=['value1','value2'],
                        index=Index(['foo','foo','foo','foo','bar','bar','bar'],
                                    name='myindex'))

In [20]: df
Out[20]: 
         value1  value2
myindex                
foo           0       1
foo           2       3
foo           4       5
foo           6       7
bar           8       9
bar          10      11
bar          12      13

[7 rows x 2 columns]

In [21]: df['count'] = df.groupby(level='myindex').cumcount()

In [22]: df
Out[22]: 
         value1  value2  count
myindex                       
foo           0       1      0
foo           2       3      1
foo           4       5      2
foo           6       7      3
bar           8       9      0
bar          10      11      1
bar          12      13      2

[7 rows x 3 columns]

You could of course add 1 to the final result if you'd like

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