我有一个非常简单的系列。
pd.Series(np.random.randn(10), dtype=np.int32)我想强制使用dtype,但是pandas会否决我的初始设置:
Out[6]:
0 0.764638
1 -1.451616
2 -0.318875
3 -1.882215
4 1.995595
5 -0.497508
6 -1.004066
7 -1.641371
8 -1.271198
9 0.907795
dtype: float64我知道我能做到:
pd.Series(np.random.randn(10), dtype=np.int32).astype("int32")
但我的问题是:为什么pandas不能在Series构造函数中以我想要的方式处理数据?没有force参数或类似的东西。
有人能解释一下那里发生了什么吗?我如何在序列构造函数中强制使用dtype,或者如果输出与我最初想要的不同,至少会得到一个警告?
发布于 2021-07-15 22:29:41
您可以使用以下命令:
>>> pd.Series(np.random.randn(10).astype(np.int32))
0 0
1 1
2 1
3 1
4 0
5 0
6 -1
7 0
8 0
9 0
dtype: int32Pandas可以正确推断数据类型。您可以强制您的数据类型,但有一个例外。如果您的数据是float,并且您希望强制dtype为intX,那么这将不起作用,因为pandas不承担丢失信息和截断结果的责任。这就是为什么你会有这样的行为。
>>> np.random.randn(10).dtype
dtype('float64')
>>> pd.Series(np.random.randn(10)).dtype
dtype('float64') # OK
>>> pd.Series(np.random.randn(10), dtype=np.int32).dtype
dtype('float64') # KO -> Pandas does not truncate the data
>>> np.random.randint(1, 10, 10).dtype
dtype('int64')
>>> pd.Series(np.random.randint(1, 10, 10)).dtype
dtype('int64') # OK
>>> pd.Series(np.random.randint(1, 10, 10), dtype=np.float64).dtype
dtype('float64') # OK -> float64 is a super set of int64https://stackoverflow.com/questions/68395571
复制相似问题