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

时间:2014-04-10 16:49:45

标签: python pandas

在像这样的DataFrame中,马是索引,如何生成一个列,它创建一个递增1的整数?

启动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

......对此...

                  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

1 个答案:

答案 0 :(得分:2)

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]

如果你想要

,你当然可以在最终结果中加1