gpt4 book ai didi

python - 我可以将 str 类型的系列转换为数字

转载 作者:行者123 更新时间:2023-11-30 22:50:12 26 4
gpt4 key购买 nike

考虑 str 类型系列 s

s = pd.Series(['a', '1'])
<小时/>
pd.to_numeric(s, 'ignore')

0 a
1 1
dtype: object
<小时/>
pd.to_numeric(s, 'ignore').apply(type)

0 <type 'str'>
1 <type 'str'>
dtype: object

显然,这两种类型仍然是字符串。看来 'ignore' 选项会忽略整个系列转换。我如何让它做它能做的事情并忽略其余的。

我希望系列类型为

pd.to_numeric(s, 'ignore').apply(type)

0 <type 'str'>
1 <type 'int'>
dtype: object
<小时/>

编辑:我在发布问题并 @ayhan 提供答案后想到了这个。

我的解决方案
不是矢量化,但给了我正是我想要的

s.apply(pd.to_numeric, errors='ignore')

最佳答案

这就是我正在使用的:

pd.to_numeric(s, errors='coerce').fillna(s)
Out:
0 a
1 1
dtype: object
<小时/>
pd.to_numeric(s, errors='coerce').fillna(s).apply(type)
Out:
0 <class 'str'>
1 <class 'float'>
dtype: object

关于python - 我可以将 str 类型的系列转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39493348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com