shift
将我的列从整数转换为 float 。事实证明 np.nan
只是 float 。有什么方法可以将移位后的列保持为整数吗?
df = pd.DataFrame({"a":range(5)})
df['b'] = df['a'].shift(1)
df['a']
# 0 0
# 1 1
# 2 2
# 3 3
# 4 4
# Name: a, dtype: int64
df['b']
# 0 NaN
# 1 0
# 2 1
# 3 2
# 4 3
# Name: b, dtype: float64
最佳答案
pandas 0.24以下解决方案:
问题是你得到 NaN
值什么是 float
,所以 int
被转换为 float
- 见 na type promotions .
一种可能的解决方案是将 NaN
值转换为某些值,如 0
,然后可能转换为 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
Pandas 0.24+ 的解决方案 - 检查 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)
关于python - pandas shift 将我的列从整数转换为 float 。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41870093/