如何更改变量以匹配pandas dtype?

时间:2015-12-01 17:17:15

标签: python numpy pandas

我想要一个确定pandas系列dtype的函数,然后更改另一个变量以匹配该类型,例如:

之类的东西
def matchtype(pandas_series, variable):
    ...
    return variable_with_new_type

我可以做以下事情:

>>> import numpy as np
>>> newtype = np.int64
>>> print(newtype)
<class 'numpy.int64'>
>>> print(newtype(3.0))
3

但它不适用于dtype:

>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({'a': [1,2]})
>>> newtype = df.a.dtype
>>> print(newtype)
int64
>>> print newtype(3.0)
        ---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)
<ipython-input-6-5a5d48ddbb52> in <module>()
----> 1 print(newtype(3.0))

TypeError: 'numpy.dtype' object is not callable

1 个答案:

答案 0 :(得分:2)

只需添加一个额外的.type即可深入了解numpy dtype对象下面的基础可调用类型:

>>> df = pd.DataFrame({'a': [1,2]})
>>> newtype = df.a.dtype.type
>>> newtype
<class 'numpy.int64'>
>>> newtype(3.0)
3
>>> type(_)
<class 'numpy.int64'>