Pandas Series - 在 Series 构造函数中强制 dtype

Pandas Series - force dtype in Series constructor

我有这个非常简单的系列。

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 或者至少在输出与我最初想要的不同时得到警告吗?

你可以使用这个:

>>> 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: int32

Pandas 正确推断数据类型。您可以强制您的数据类型,但有一个例外。如果你的数据是 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 int64