何时申请(pd.to_numeric)以及何时在python中使用astype(np.float64)?

d8a*_*nja 30 python types numpy dataframe pandas

我有一个名为pandas的DataFrame对象xiv,它有一列int64Volume测量值.

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

0    252000
1    484000
2     62000
3    168000
4    232000
Name: Volume, dtype: int64
Run Code Online (Sandbox Code Playgroud)

我已经阅读了其他帖子(比如这个这个),提出了以下解决方案.但是,当我使用任何一种方法时,它似乎不会改变dtype底层数据:

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

In[]: xiv['Volume'].dtypes
Out[]: 
dtype('int64')
Run Code Online (Sandbox Code Playgroud)

要么...

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')
Run Code Online (Sandbox Code Playgroud)

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

但是,我已经使用numpy包的float64类型找到了解决这个问题的方法- 这有效,但我不知道它为什么会有所不同.

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

In[]: xiv['Volume'].dtypes
Out[]: 
dtype('float64') 
Run Code Online (Sandbox Code Playgroud)

有人可以解释如何使用pandas库来完成numpy库似乎可以轻松地使用它的float64类; 也就是说,将xivDataFrame中的列转换为float64适当的位置.

Max*_*axU 34

如果您已经拥有数字dtypes( ,int8|16|32|64,float64),boolean你可以将其转换为使用另一种"数字" D型熊猫 .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
Run Code Online (Sandbox Code Playgroud)

它不适用于无法转换为数字的object(字符串)dtypes :

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'
Run Code Online (Sandbox Code Playgroud)

所以这里我们要使用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
Run Code Online (Sandbox Code Playgroud)