How to move every element in a column by n range in a dataframe using python?

Viewed 131

I have a dataframe df that looks like below:

No  A   B   value
1   23  36   1
2   45  23   1
3   34  12   2
4   22  76   NaN
...

I would like to shift each of the value in "value" column by 2. And the first row "value" should not be shifted.

I have already tried the normal shift, which directly shifts everthing by 2.

df['value']=df['value'].shift(2)

i expect the below result:

No  A   B   value
1   23  36   1
2   45  23   Nan
3   34  12   Nan
4   22  76   1
5   10  12   Nan
6   34  2    Nan
7   21  11   2
...

1 Answers

In your case

df['Newvalue']=pd.Series(df.value.values,index=np.arange(len(df))*3)
df
Out[41]: 
   No   A   B  value  Newvalue
0   1  23  36    1.0       1.0
1   2  45  23    1.0       NaN
2   3  34  12    2.0       NaN
3   4  22  76    NaN       1.0
Related