1

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
petezurich
  • 9,280
  • 9
  • 43
  • 57
Shengxin Huang
  • 647
  • 1
  • 11
  • 25
  • It looks like you are trying to achieve this https://stackoverflow.com/questions/33907537/groupby-and-lag-all-columns-of-a-dataframe – jyr Jul 29 '22 at 07:41

1 Answers1

1

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
mozway
  • 194,879
  • 13
  • 39
  • 75