pandas shift converts my column from integer to float.

后端 未结 5 1185
一整个雨季
一整个雨季 2020-12-10 12:14

shift converts my column from integer to float. It turns out that np.nan is float only. Is there any ways to keep shifted column as integer?

<
5条回答
  •  庸人自扰
    2020-12-10 12:48

    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)
    

提交回复
热议问题