Pandas: 获取列数据类型为字符串

Pandas: Get column dtype as string

给定一个系列和一个列的(唯一)dtype,我希望里面的 dtype 信息是一个字符串。

import numpy as np
import pandas as pd

df = pd.DataFrame(columns = ['col1', 'col2'], data = [[1,2], [3,4]])
df.dtypes[0]

上面代码的输出

目标:从df.dtypes[0]中提取字符串'int64',即dtype('int64').

一直没有在网上找到解决办法。

简单转换为字符串:

df.dtypes.astype(str)[0]

或者如果您真的只对单个值感兴趣,请使用 name 属性。

df.dtypes[0].name

输出:'int64'

对于整个系列:

>>> df.dtypes.astype(str)
col1    int64
col2    int64
dtype: object