有关如何将系列(列)从float转换为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
答案 0 :(得分:2)
你不能这样投射,你需要做
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可能会在你对它执行某些操作时被转换失去了你的初衷