gpt4 book ai didi

python - 如何更改变量以匹配 pandas 数据类型?

转载 作者:行者123 更新时间:2023-12-01 04:18:27 25 4
gpt4 key购买 nike

我想要一个函数来确定 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

但它不适用于数据类型:

>>> 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

最佳答案

只需添加一个额外的 .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'>

关于python - 如何更改变量以匹配 pandas 数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34026166/

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