Search code examples
pythonpython-3.xpandasdataframeshift

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.

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