python-3.x - 类型错误 : conversion from Series to Decimal is not supported

标签 python-3.x pandas numpy decimal

关于如何将系列(列)从浮点数转换为十进制数的任何想法?我在 Python 3.6 上。我已经阅读了 Decimal 文档,但它没有提供任何帮助。

df['rate'].dtype
Out[158]: dtype('float64')
Decimal(df['rate'])
Traceback (most recent call last):
  File "C:\Users\user\Anaconda3\lib\site-packages\IPython
   \core\interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
    File "<ipython-input-159-88710e11f7cd>", line 1, in <module>
    Decimal(df['rate'])
 TypeError: conversion from Series to Decimal is not supported

最佳答案

你不能像这样投,你需要做

df['rate'] = df['rate'].apply(Decimal)
pandas 确实支持 Decimal 但你不能那样转换

例子:
In[28]:
from decimal import *
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
df['a'] = df['a'].apply(Decimal)
df

Out[28]: 
                                                   a         b         c
0  -1.6122557830197199457700207858579233288764953... -1.865243 -0.836893
1  0.96962430214434858211092205237946473062038421... -0.105823 -0.842267
2  -0.9113389075755260471112251252634450793266296... -0.351389 -0.183489
3  1.22765470106414120721183280693367123603820800... -1.232627 -0.067909
4  -0.0376339704393285762185072940155805554240942... -0.445606 -0.080623

dtype 仍会显示 object 但 dtype 确实是 Decimal :
In[29]:
type(df['a'].iloc[0])

Out[29]: decimal.Decimal

如果你使用 astype(Decimal) 它看起来像它工作但它没有:
In[38]:
df['b'].astype(Decimal)

Out[38]: 
0    -1.86524
1   -0.105823
2   -0.351389
3    -1.23263
4   -0.445606
Name: b, dtype: object

如果我们尝试将其分配回来:
In[39]:
df['b'] = df['b'].astype(Decimal)
type(df['b'].iloc[0])

Out[39]: float

正如@JonClements 所指出的,我同意使用非本地 numpy 类型是不明智的,因为您会丢失任何向量化,尤其是算术运算,此外,当您对其执行某些操作时,dtype 可能会被转换,然后会丢失您的原始数据意图

关于python-3.x - 类型错误 : conversion from Series to Decimal is not supported,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47266531/

相关文章:

python-3.x - 如何在 Python 3 中使用具有多个参数的多处理?

Python3 turtle 将代码保存到文件

python - 多索引数据框中列之间的数学运算

python - 提高在列表中查找项目索引的速度

python - Conda安装包ModuleNotFoundError : No module named 'conda'

python-3.x - 如何在 digital ocean 上的 Ubuntu VPS 上安装 dlib

python - 如何在 Python 中创建数据框数组

python - 在python中按数字部分按升序对包含数字和字母的字符串列进行排序

python - 将行和列的总和附加到矩阵

python - 以最有效的方式从数字 numpy 数组中获取 0 和 1(整数 bool 值)