'Python Pandas Increment Counter Column

I have a dataframe and I intend to add a counter column. It should start with a value x and for every new row it should increase incrementally by the same value y. I already tried to apply this code:

initial_value = x
df["Counter"] = range(initial_value, len(df) + initial_value) 

But I am not sure how to continue. Does anyone have an idea?

Thank you!



Solution 1:[1]

Simply :

df["Counter"] = list(range(x, len(df)*y+x, y)) 

or Using numpy:

df["Counter"] = np.arange(start=x, step=y, stop=len(df)*y+x)

Solution 2:[2]

The simplest solution would be to simply loop over the entire dataframe, and to calculate the values like this:

df['new_col'] = start_value
for i in range(len(df)):
     df['new_col'][i] = df['new_col'][i-1] + increment_value

You can also use apply method to achieve the desired result.

df['col1'] = df.apply(lambda x: start_value + df.index*increment_value)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Prats