为重复项添加增量值

2024-04-18 11:16:48 发布

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

假设我有一个看起来像

df = pd.DataFrame(np.array([[1, 2, 3, 2], [4, 5, 6, 3], [7, 8, 9, 5]]),  columns=['a', 'b', 'c', 'repeater'])

    a   b   c   repeater
0   1   2   3   2
1   4   5   6   3
2   7   8   9   5

我根据类似df['repeat']df = df.loc[df.index.repeat(df['repeater'])]重复每一行 所以我最终得到了一个数据帧

    a   b   c   repeater
0   1   2   3   2
0   1   2   3   2
1   4   5   6   3
1   4   5   6   3
1   4   5   6   3
2   7   8   9   5
2   7   8   9   5
2   7   8   9   5
2   7   8   9   5
2   7   8   9   5

如何基于索引行添加增量值?因此,一个新列df['incremental']具有以下输出:

    a   b   c   repeater    incremental
0   1   2   3   2           1
0   1   2   3   2           2
1   4   5   6   3           1
1   4   5   6   3           2
1   4   5   6   3           3
2   7   8   9   5           1
2   7   8   9   5           2
2   7   8   9   5           3
2   7   8   9   5           4
2   7   8   9   5           5

Tags: columns数据dataframedfindexnparray增量
1条回答
网友
1楼 · 发布于 2024-04-18 11:16:48

使用额外的groupbycumcount尝试您的代码:

df = df.loc[df.index.repeat(df['repeater'])]
df['incremental'] = df.groupby(df.index).cumcount() + 1
print(df)

输出:

   a  b  c  repeater  incremental
0  1  2  3         2            1
0  1  2  3         2            2
1  4  5  6         3            1
1  4  5  6         3            2
1  4  5  6         3            3
2  7  8  9         5            1
2  7  8  9         5            2
2  7  8  9         5            3
2  7  8  9         5            4
2  7  8  9         5            5

相关问题 更多 >