在索引数据框中生成编号行

2024-04-26 20:22:16 发布

您现在位置:Python中文网/ 问答频道 /正文

在这样一个以horse为索引的数据帧中,如何生成一个列来创建一个递增1的整数?你知道吗

正在启动数据帧。。。你知道吗

                  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

Tags: 数据line整数rowlastracehorsegunfighter
1条回答
网友
1楼 · 发布于 2024-04-26 20:22:16
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

相关问题 更多 >