Elham
Elham

Reputation: 867

Shifting a Row in Python-Pandas

I am new to Pandas and I have a question which I could not fix it by myself. This is my column

0       12.000000

1       21.540659

2       19.122413

3     16.568042

4     17.082154

5     15.932148

6     15.226856

7     14.400521

8     17.900962

9     17.169741

10          NaN

and I want to shift it by one row.The expected result should be looks like this:

0           NaN

1     12.000000

2     21.540659

3     19.122413

4     16.568042

5     17.082154

6     15.932148

7     15.226856

8     14.400521

9     17.900962

10    17.169741

Here is my code:

data['A']=pd.Series(a).shift(periods=1)

a is a list and I convert it to the pandas series to add a new column as an "A" in my dataframe. Howerevr I need to shift my rows without losing the last data.

Upvotes: 2

Views: 7626

Answers (3)

FabienP
FabienP

Reputation: 3138

You can use np.roll for that.

Answer found here, check the link for details.

Upvotes: 0

Anton vBR
Anton vBR

Reputation: 18906

Wait now? Doesn't this work?

data["A"] = data["A"].shift(1)

Upvotes: 4

Scott Boston
Scott Boston

Reputation: 153460

IIUC,

You could pad your Series creation with an extra row then shift:

data['A'] = pd.Series(a+[pd.np.nan]).shift(1)

Upvotes: 1

Related Questions