python - Python 中 R 的 seq_len 等价物

标签 python r pandas refactoring

<分区>

我正在尝试在我的 data.frame 中的组内进行索引

例如,在这个数据框中

Col1
A
A
A
B
B
C
D
D
D

我想输出如下

Col1    idx
A   1
A   2
A   3
B   1
B   2
C   1
D   1
D   2
D   3

在 R 中,我可以使用 data.table df[, idx:=seq_len(.N), by=Col1] 简单地执行以下操作。我在 Python 中找不到等效项。到目前为止,我知道我可以在 numpy 的包中使用 linspacearrange 函数,但我不太清楚该怎么做按组。

提前谢谢你。

最佳答案

使用累积计数

In [289]: df['idx'] = df.groupby('Col1').cumcount().add(1)

In [290]: df
Out[290]:
  Col1  idx
0    A    1
1    A    2
2    A    3
3    B    1
4    B    2
5    C    1
6    D    1
7    D    2
8    D    3

关于python - Python 中 R 的 seq_len 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50548935/

相关文章:

python - Pandas 迭代更新列值

R CMD 检查警告 : Non-standard license specification

python - 基于 bool 条件的 Pandas 数据框中的新列

PYTHON - 查找数组中每 10 个整数的最大值

python - 在 Python 中,是否可以从函数内访问全局命名空间

python - Mayavi 如何显示轴网格

python - 使用 Anaconda 安装 pygame

r - 无法使用 rapache 打开文件 'Rplots.pdf'

r - 如何rbind多个表

Pandas 情节 axvspan