Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use `df.shift(n)` in pandas dataframe such that I can bring `n` item from bottom to the top instead of `nan` values or vice versa?

I have a pandas dataframe df containing 5 rows and 2 columns.

A   B
0   10  0
1   20  5
2   30  10
3   40  15
4   50  20

df.to_dict() returns

{'A': {0: 10, 1: 20, 2: 30, 3: 40, 4: 50},
 'B': {0: 0, 1: 5, 2: 10, 3: 15, 4: 20}}

For column A, I want to shift each item to two rows below. Instead of having nan values on top, I want to bring two elements that would be pushed out in the bottom to the top.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For column B, I want to do the opposite – shift each item to two rows above. Instead of having nan values on bottom, I want to bring two elements that would be pushed out in the top to the bottom.

I can use df["A"].shift(2) and df["B"].shift(-2). However, I get nan values.

My expected results is:

A   B
0   40  10
1   50  15
2   10  20
3   20  0
4   30  5

How can I achieve this?

>Solution :

Use numpy.roll instead shift:

df['A'] = np.roll(df["A"], 2)
df['B'] = np.roll(df["B"], -2)
print (df)
    A   B
0  40  10
1  50  15
2  10  20
3  20   0
4  30   5
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading