首页 > 解决方案 > 识别熊猫数据框中列的数据类型的正确方法是什么?

问题描述

我目前正在做一个项目,我需要将 pandas 数据框中的数据转换为使用不同(非 python)类型系统的另一种表示形式。pandas 的序列化/io 方法之一不涵盖转换。特别是我需要将 pandas 数据框列数据类型映射到其他类型系统的数据类型。对于初学者,我们假设目标类型系统非常简单,只有stringintegerfloatbooleantimestamp类型。

因此,我首先通过一个简单的示例查看数据帧 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]

对我的字符串列更好,但现在我Int64的整数列和浮点列(!)都得到(大写“I”),boolean而不是bool. (好吧,float64当我在示例数据中使用“真实”浮点数(例如“0.1”但仍然......)

这让我想知道我是否在正确的轨道上使用这种方法。然后我查看了numpy dtype 文档numpy dtype charcodes。但是似乎没有每种可能的数据类型的字符码,尤其是。不适用于字符串类型。此外,我在应用后获得的 pandas 扩展 dtypeconvert_dtypes()不再具有该char属性。

所以我的问题是,获取可用于将这些数据类型映射到另一个类型系统的 pandas 数据框中的列的数据类型标识符的规范方法是什么?

标签: pythonpandasdataframetypes

解决方案


df.dtypes 获取数据类型标识符的规范方法。dtype您可以为每个关联的底层 numpy dtype 代码打印<dtype>.str. 您还可以通过以下方式获得类型(整数、浮点数、...)<dtype>.kind

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 index, value in dts.items():
    print("column %s dtype[class: %s; name: %s; code: %s; kind: %s]" % (index, type(value), value.name, value.str, value.kind))

产量:

column string dtype[class: <class 'numpy.dtype'>; name: object; code: |O; kind: O]
column integer dtype[class: <class 'numpy.dtype'>; name: int64; code: <i8; kind: i]
column float dtype[class: <class 'numpy.dtype'>; name: float64; code: <f8; kind: f]
column boolean dtype[class: <class 'numpy.dtype'>; name: bool; code: |b1; kind: b]
column timestamp dtype[class: <class 'numpy.dtype'>; name: datetime64[ns]; code: <M8[ns]; kind: M]

问题是,正如您所指出的,某些数据类型是在 pandas 中专门定义的,但它们由 numpy 数据类型支持(它们具有 numpy 数据类型代码)。例如,numpy定义了datetime64[ns]你可以在上面看到的,但 pandas 在它上面定义了一个时区本地化的dtype。你可以看到 :

# localize with timezone
df['timestamp'] = pd.DatetimeIndex(df['timestamp']).tz_localize(tz='UTC')

# look at the dtype of timestamp: now a pandas dtype
index, value = 'timestamp', df.dtypes.timestamp
print("column %s dtype[class: %s; name: %s; code: %s; kind: %s]" % (index, type(value), value.name, value.str, value.kind))

产量

column timestamp dtype[class: <class 'pandas.core.dtypes.dtypes.DatetimeTZDtype'>; name: datetime64[ns, UTC]; code: |M8[ns]; kind: M]    

现在 dtype是一个自定义的 pandas 类 ( DatetimeTZDtype),而底层的 dtype 代码是一个 numpy 的。如果您使用string默认情况下不在 numpy 中的数据类型,也会发生同样的情况。

因此,总而言之,要达到您最初的目标,您应该首先查看,type(<dtype>)如果它不是自定义的 pandas,然后查看 numpy <dtype>.kind(最好是<dtype>.str因为 numpy 允许您定义多种整数(大/小端,nb 位等))。

最后,正如您所发现的,Dataframe.convert_dtypes()它是一个转换器,它具有用于选择打开/关闭哪个自动转换功能的参数。


推荐阅读