gpt4 book ai didi

python - 为重复项添加增量值

转载 作者:行者123 更新时间:2023-12-01 06:31:48 27 4
gpt4 key购买 nike

假设我有一个看起来像这样的数据框

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

最佳答案

使用额外的 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

关于python - 为重复项添加增量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59875334/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com