[英]Increment column value based on value of another column
I have a df as below:我有一个 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
I want to add a new column Value1
.我想添加一个新列Value1
。 At every repetition of ID the value in column Value
should be incremented and saved in column Value1
.每次重复 ID 时,列Value
中的值都应递增并保存在列Value1
中。 However, it should only be incremented by number given in column Counter
then it should repeat.但是,它应该只增加Counter
列中给出的数字,然后它应该重复。 Below is the desired output.下面是所需的 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
My attempt:我的尝试:
df['Value1'] = df['Value']
df['Value1'] += df.groupby('ID')['Value1'].cumcount() +1
But this does not consider the counter and just increments.但这不考虑计数器,只是增加。 How is it possible to repeat the increment after the counter value has reached.计数器值达到后如何重复增量。
You'll need to use the modulo operator to reset your .cumcount
by the value of df["counter"]
您需要使用模运算符将.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.