pandas 从numpy 借用它的数据类型。有关这一点的演示,请参见以下内容:
import pandas as pd
df = pd.DataFrame({'A': [1,'C',2.]})
df['A'].dtype
>>> dtype('O')
type(df['A'].dtype)
>>> numpy.dtype
你可以找到有效numpy.dtypesin the documentation的列表:
'?'布尔值
'b'(有符号)字节
'B' 无符号字节
'i'(有符号)整数
'u'无符号整数
'f' 浮点数
'c' 复数浮点数
'm'时间增量
'M' 日期时间
'O' (Python) 对象
'S', 'a' 以零结尾的字节(不推荐)
'U' Unicode 字符串
'V' 原始数据(无效)
pandas 应该支持这些类型。使用带有上述任何选项的pandas.Series 对象的astype 方法作为输入参数将导致pandas 尝试将Series 转换为该类型(或至少回退到object类型); 'u' 是我看到的唯一一个 pandas 完全不理解:
df['A'].astype('u')
>>> TypeError: data type "u" not understood
这是一个numpy 错误,因为'u' 后面需要一个数字来指定每个项目的字节数(必须是有效的):
import numpy as np
np.dtype('u')
>>> TypeError: data type "u" not understood
np.dtype('u1')
>>> dtype('uint8')
np.dtype('u2')
>>> dtype('uint16')
np.dtype('u4')
>>> dtype('uint32')
np.dtype('u8')
>>> dtype('uint64')
# testing another invalid argument
np.dtype('u3')
>>> TypeError: data type "u3" not understood
总而言之,pandas 对象的astype 方法将尝试对任何对numpy.dtype 有效的参数做一些明智的事情。请注意,numpy.dtype('f') 与 numpy.dtype('float32') 相同,numpy.dtype('f8') 与 numpy.dtype('float64') 等相同。将参数传递给 pandas astype 方法也是如此。
要在 NumPy 中定位相应的数据类型类,Pandas docs 建议这样做:
def subdtypes(dtype):
subs = dtype.__subclasses__()
if not subs:
return dtype
return [dtype, [subdtypes(dt) for dt in subs]]
subdtypes(np.generic)
输出:
[numpy.generic,
[[numpy.number,
[[numpy.integer,
[[numpy.signedinteger,
[numpy.int8,
numpy.int16,
numpy.int32,
numpy.int64,
numpy.int64,
numpy.timedelta64]],
[numpy.unsignedinteger,
[numpy.uint8,
numpy.uint16,
numpy.uint32,
numpy.uint64,
numpy.uint64]]]],
[numpy.inexact,
[[numpy.floating,
[numpy.float16, numpy.float32, numpy.float64, numpy.float128]],
[numpy.complexfloating,
[numpy.complex64, numpy.complex128, numpy.complex256]]]]]],
[numpy.flexible,
[[numpy.character, [numpy.bytes_, numpy.str_]],
[numpy.void, [numpy.record]]]],
numpy.bool_,
numpy.datetime64,
numpy.object_]]
Pandas 接受这些类作为有效类型。例如,dtype={'A': np.float}。
NumPy 文档contain 更多详细信息和图表: