A solution for pandas under 0.24:
The problem is you get a NaN
value that 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 it 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
A 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)
df['b'] = df['a'].shift(1).fillna(-1).astype(df.a.dtype)