Solution for pandas under 0.24:
Problem is you get NaN
value what is float
, so int
is converted to float
- see na type promotions.
One possible solution is convert NaN
values to some value like 0
and then is possible convert to int
:
df = pd.DataFrame({"a":range(5)})
df['b'] = df['a'].shift(1).fillna(0).astype(int)
print (df)
a b
0 0 0
1 1 0
2 2 1
3 3 2
4 4 3
Solution for pandas 0.24+ - check Series.shift
:
fill_value object, optional
The scalar value to use for newly introduced missing values. the default depends on the dtype of self. For numeric data, np.nan is used. For datetime, timedelta, or period data, etc. NaT is used. For extension dtypes, self.dtype.na_value is used.
Changed in version 0.24.0.
df['b'] = df['a'].shift(fill_value=0)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…