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!
CodePudding user response:
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)
CodePudding user response:
df["Counter"] = [ i for i in range(x, x y*(len(df.index)), y) ]
CodePudding user response:
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)