简体   繁体   English

在索引的Pandas DataFrame中生成编号的行

[英]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? 在像这样的DataFrame中,马是索引,如何生成一个列,它创建一个递增1的整数?

Starting DataFrame... 启动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 如果您愿意,您当然可以在最终结果中加1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM