首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Pandas Series - Series构造函数中的force dtype

Pandas Series - Series构造函数中的force dtype
EN

Stack Overflow用户
提问于 2021-07-15 22:18:20
回答 1查看 28关注 0票数 0

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

代码语言:javascript
复制
pd.Series(np.random.randn(10), dtype=np.int32)

我想强制使用dtype,但是pandas会否决我的初始设置:

代码语言:javascript
复制
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,或者如果输出与我最初想要的不同,至少会得到一个警告?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-15 22:29:41

您可以使用以下命令:

代码语言:javascript
复制
>>> 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不承担丢失信息和截断结果的责任。这就是为什么你会有这样的行为。

代码语言:javascript
复制
>>> 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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68395571

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档