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
import pandas as pddf = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],'age':[18, 39, 22, 45],'price': [1.0, 2.0, 3.0, 4.0],'color': ['red', 'black', None, 'red']}, index=['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04'])df.shift(periods=2)-------------------------------------------------------------------site age price color2021-01-01 NaN NaN NaN NaN2021-01-02 NaN NaN NaN NaN2021-01-03 google 18.0 1.0 red2021-01-04 baidu 39.0 2.0 black
Example
import pandas as pddf = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],'age':[18, 39, 22, 45],'price': [1.0, 2.0, 3.0, 4.0],'color': ['red', 'black', None, 'red']}, index=['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04'])df.shift(periods=1, axis='columns')---------------------------------------------------------site age price color2021-01-01 NaN google 18 1.02021-01-02 NaN baidu 39 2.02021-01-03 NaN wiki 22 3.02021-01-04 NaN pandas 45 4.0
Example
import pandas as pddf = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],'age':[18, 39, 22, 45],'price': [1.0, 2.0, 3.0, 4.0],'color': ['red', 'black', None, 'red']}, index=['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04'])df.shift(periods=1, fill_value=0)--------------------------------------------------------------------site age price color2021-01-01 0 0 0.0 02021-01-02 google 18 1.0 red2021-01-03 baidu 39 2.0 black2021-01-04 wiki 22 3.0 None
