gpt4 book ai didi

python - 何时在 python 中应用(pd.to_numeric)和何时 astype(np.float64)?

转载 作者:IT老高 更新时间:2023-10-28 22:12:20 29 4
gpt4 key购买 nike

我有一个名为 xiv 的 pandas DataFrame 对象,其中有一列 int64 体积测量值。

In[]: xiv['Volume'].head(5)
Out[]:

0 252000
1 484000
2 62000
3 168000
4 232000
Name: Volume, dtype: int64

我已阅读其他建议以下解决方案的帖子(如 thisthis )。但是当我使用任何一种方法时,它似乎都不会改变底层数据的 dtype :

In[]: xiv['Volume'] = pd.to_numeric(xiv['Volume'])

In[]: xiv['Volume'].dtypes
Out[]:
dtype('int64')

或者……

In[]: xiv['Volume'] = pd.to_numeric(xiv['Volume'])
Out[]: ###omitted for brevity###

In[]: xiv['Volume'].dtypes
Out[]:
dtype('int64')

In[]: xiv['Volume'] = xiv['Volume'].apply(pd.to_numeric)

In[]: xiv['Volume'].dtypes
Out[]:
dtype('int64')

我还尝试制作一个单独的 Pandas Series 并使用上面列出的该系列的方法并重新分配给 x['Volume'] 对象,即pandas.core.series.Series 对象。

不过,我找到了使用 numpy 包的 float64 类型的解决方案 - 这可行,但我不知道为什么这是不同的

In[]: xiv['Volume'] = xiv['Volume'].astype(np.float64)

In[]: xiv['Volume'].dtypes
Out[]:
dtype('float64')

有人能解释一下如何使用 pandas 库来完成 numpy 库似乎可以通过其 float64 类轻松完成的工作吗?也就是将xiv DataFrame中的列原地转换成float64

最佳答案

如果您已经有数字 dtypes (int8|16|32|64,float64,boolean),您可以将其转换为另一个“numeric"dtype 使用 Pandas .astype() 方法。

演示:

In [90]: df = pd.DataFrame(np.random.randint(10**5,10**7,(5,3)),columns=list('abc'), dtype=np.int64)

In [91]: df
Out[91]:
a b c
0 9059440 9590567 2076918
1 5861102 4566089 1947323
2 6636568 162770 2487991
3 6794572 5236903 5628779
4 470121 4044395 4546794

In [92]: df.dtypes
Out[92]:
a int64
b int64
c int64
dtype: object

In [93]: df['a'] = df['a'].astype(float)

In [94]: df.dtypes
Out[94]:
a float64
b int64
c int64
dtype: object

它不适用于 object(字符串)dtype,不能转换为数字:

In [95]: df.loc[1, 'b'] = 'XXXXXX'

In [96]: df
Out[96]:
a b c
0 9059440.0 9590567 2076918
1 5861102.0 XXXXXX 1947323
2 6636568.0 162770 2487991
3 6794572.0 5236903 5628779
4 470121.0 4044395 4546794

In [97]: df.dtypes
Out[97]:
a float64
b object
c int64
dtype: object

In [98]: df['b'].astype(float)
...
skipped
...
ValueError: could not convert string to float: 'XXXXXX'

所以这里我们要使用pd.to_numeric()方法:

In [99]: df['b'] = pd.to_numeric(df['b'], errors='coerce')

In [100]: df
Out[100]:
a b c
0 9059440.0 9590567.0 2076918
1 5861102.0 NaN 1947323
2 6636568.0 162770.0 2487991
3 6794572.0 5236903.0 5628779
4 470121.0 4044395.0 4546794

In [101]: df.dtypes
Out[101]:
a float64
b float64
c int64
dtype: object

关于python - 何时在 python 中应用(pd.to_numeric)和何时 astype(np.float64)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40095712/

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