【发布时间】:2021-03-16 21:35:39
【问题描述】:
我目前正在开展一个项目,我需要将 pandas 数据框中的数据转换为使用不同(非 python)类型系统的另一种表示形式。 pandas 的serialization/io methods 之一没有涵盖转换。特别是我需要将 pandas 数据框列数据类型映射到其他类型系统的数据类型。对于初学者,我们假设目标类型系统非常简单,只有 string、integer、float、boolean 和 timestamp 类型。
所以,我首先通过一个简单的示例查看dataframe dtypes:
import pandas as pd
from datetime import datetime
headers = ["string", "integer", "float", "boolean", "timestamp"]
data = [["a", 1, 1.0, True, datetime.now()]]
df = pd.DataFrame(data, columns=headers)
dts = df.dtypes
for col in dts.index:
print("column: ", col, " - type: ", dts[col].name)
这给了我:
column: string - type: object
column: integer - type: int64
column: float - type: float64
column: boolean - type: bool
column: timestamp - type: datetime64[ns]
好的,为字符串列获取object 并不好,所以我找到了Dataframe.convert_dtypes() 方法,当它添加到数据框创建行时给了我:
column: string - type: string
column: integer - type: Int64
column: float - type: Int64
column: boolean - type: boolean
column: timestamp - type: datetime64[ns]
更适合我的字符串列,但现在我的整数列和浮点列 (!) 和 boolean 都得到了 Int64(带有大写“I”),而不是 bool。 (好的,当我在示例数据中使用诸如“0.1”之类的“真实”浮点数时,我回到float64,但仍然......)
这让我想知道我是否在正确的轨道上使用这种方法。然后我查看了numpy dtype documentation 和numpy dtype charcodes。但是似乎没有针对每种可能的数据类型的字符码,尤其是。不适用于字符串类型。此外,我在应用 convert_dtypes() 后获得的 pandas 扩展 dtype 不再具有 char 属性。
所以我的问题是,获取可用于将这些数据类型映射到另一个类型系统的 pandas 数据框中的列的数据类型标识符的规范方法是什么?
【问题讨论】:
标签: python pandas dataframe types