簡體   English   中英

在索引的Pandas DataFrame中生成編號的行

[英]Generate numbered rows in indexed Pandas DataFrame

在像這樣的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
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM