DataFrame.shift

DataFrame.shift(periods=1, freq=None, axis=0, fill_value=)
使用可选的时间频率按所需的周期数移动索引。

Parameters

periods 要移动的周期数。可以是正也可以是负。
freq 偏移量
axis 0或index:行偏移;1或columns:列偏移
fill_value 用于新引入的缺失值的标量值,默认值取决于self的dtype。
- 对于数值数据:np.nan;
- 对于日期时间:NaT;
- 对于扩展数据:self.dtype.na_value

Example

  1. import pandas as pd
  2. df = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],
  3. 'age':[18, 39, 22, 45],
  4. 'price': [1.0, 2.0, 3.0, 4.0],
  5. 'color': ['red', 'black', None, 'red']}, index=['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04'])
  6. df.shift(periods=2)
  7. -------------------------------------------------------------------
  8. site age price color
  9. 2021-01-01 NaN NaN NaN NaN
  10. 2021-01-02 NaN NaN NaN NaN
  11. 2021-01-03 google 18.0 1.0 red
  12. 2021-01-04 baidu 39.0 2.0 black

Example

  1. import pandas as pd
  2. df = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],
  3. 'age':[18, 39, 22, 45],
  4. 'price': [1.0, 2.0, 3.0, 4.0],
  5. 'color': ['red', 'black', None, 'red']}, index=['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04'])
  6. df.shift(periods=1, axis='columns')
  7. ---------------------------------------------------------
  8. site age price color
  9. 2021-01-01 NaN google 18 1.0
  10. 2021-01-02 NaN baidu 39 2.0
  11. 2021-01-03 NaN wiki 22 3.0
  12. 2021-01-04 NaN pandas 45 4.0

Example

  1. import pandas as pd
  2. df = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],
  3. 'age':[18, 39, 22, 45],
  4. 'price': [1.0, 2.0, 3.0, 4.0],
  5. 'color': ['red', 'black', None, 'red']}, index=['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04'])
  6. df.shift(periods=1, fill_value=0)
  7. --------------------------------------------------------------------
  8. site age price color
  9. 2021-01-01 0 0 0.0 0
  10. 2021-01-02 google 18 1.0 red
  11. 2021-01-03 baidu 39 2.0 black
  12. 2021-01-04 wiki 22 3.0 None