Shengxin Huang
Shengxin Huang

Reputation: 707

How to shift every certain rows in a dataframe?

Could anyone please tell me how to achieve this?

The original dataframe is like:

                  value
2021-4-22          1
2021-4-23          22
2021-4-26          31
2021-4-27          42
2021-10-11         12
2021-10-13         15
2021-10-15         54
2021-10-16         65
2022-02-21         27
2022-02-22         23
2022-02-23         78
2022-02-24         56

For example ,I want to shift my data by 1 row with every 4 rows as a group:

                  value
2021-4-22          nan
2021-4-23          1
2021-4-26          22
2021-4-27          31
2021-10-11         nan
2021-10-13         12
2021-10-15         15
2021-10-16         54
2022-02-21         nan
2022-02-22         27
2022-02-23         23
2022-02-24         78

Upvotes: 1

Views: 48

Answers (1)

mozway
mozway

Reputation: 260410

It looks like you want to shift per month. Use the index to create a monthly period, then groupby.shift:

group = pd.to_datetime(df.index).to_period('M')
out = df.groupby(group).shift()

If you really want to use a fixed number (N=4):

N=4
group = np.arange(len(df))//N
out = df.groupby(group).shift()

output:

            value
2021-4-22     NaN
2021-4-23     1.0
2021-4-26    22.0
2021-4-27    31.0
2021-10-11    NaN
2021-10-13   12.0
2021-10-15   15.0
2021-10-16   54.0
2022-02-21    NaN
2022-02-22   27.0
2022-02-23   23.0
2022-02-24   78.0

Upvotes: 1

Related Questions