[英]Increment column value based on value of another column
我有一个 df 如下:
ID Value counter
0 A 30 3
1 A 30 3
2 A 30 3
3 A 30 3
4 A 30 3
5 A 30 3
6 B 50 2
7 B 50 2
8 B 50 2
9 B 50 2
10 C 40 2
11 C 40 2
12 C 40 2
13 C 40 2
我想添加一个新列Value1
。 每次重复 ID 时,列Value
中的值都应递增并保存在列Value1
中。 但是,它应该只增加Counter
列中给出的数字,然后它应该重复。 下面是所需的 output。
ID Value counter Value1
0 A 30 3 31
1 A 30 3 32
2 A 30 3 33
3 A 30 3 31
4 A 30 3 32
5 A 30 3 33
6 B 50 2 51
7 B 50 2 52
8 B 50 2 51
9 B 50 2 52
10 C 40 2 41
11 C 40 2 42
12 C 40 2 41
13 C 40 2 42
我的尝试:
df['Value1'] = df['Value']
df['Value1'] += df.groupby('ID')['Value1'].cumcount() +1
但这不考虑计数器,只是增加。 计数器值达到后如何重复增量。
您需要使用模运算符将.cumcount
重置为df["counter"]
的值
df["Value1"] = (
df["Value"] + df.groupby("ID")["Value"].cumcount().mod(df["counter"]).add(1)
)
print(df)
ID Value counter Value1
0 A 30 3 31
1 A 30 3 32
2 A 30 3 33
3 A 30 3 31
4 A 30 3 32
5 A 30 3 33
6 B 50 2 51
7 B 50 2 52
8 B 50 2 51
9 B 50 2 52
10 C 40 2 41
11 C 40 2 42
12 C 40 2 41
13 C 40 2 42
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.