pandas 数组、标量和数据类型#

对象#

对于大多数数据类型,pandas 在 IndexSeriesDataFrame 中包含的具体对象使用 NumPy 数组。

对于某些数据类型,pandas 扩展了 NumPy 的类型系统。这些类型的字符串别名可以在 数据类型 中找到。

数据种类

pandas 数据类型

标量

数组

带时区日期时间

DatetimeTZDtype

Timestamp

日期时间

Timedeltas

(无)

Timedelta

Timedeltas

周期(时间跨度)

PeriodDtype

Period

Periods

区间

IntervalDtype

Interval

区间

可空整数

Int64Dtype,...

(无)

可空整数

可空浮点数

Float64Dtype,...

(无)

可空浮点数

Categorical

CategoricalDtype

(无)

分类数据

Sparse

SparseDtype

(无)

Sparse

字符串

StringDtype

str

字符串

可空布尔值

BooleanDtype

bool

可空布尔值

PyArrow

ArrowDtype

Python 标量或 NA

PyArrow

pandas 和第三方库可以扩展 NumPy 的类型系统(参见 扩展类型)。顶层 array() 方法可用于创建新数组,该数组可能存储在 SeriesIndex 中,或作为 DataFrame 的列。

array(data[, dtype, copy])

创建数组。

PyArrow#

警告

此功能处于实验阶段,API 可能会在未来版本中更改,恕不另行通知。

arrays.ArrowExtensionArray 类由 pyarrow.ChunkedArray 支持,其 pyarrow.DataType 而非 NumPy 数组和数据类型。pandas.arrays.ArrowExtensionArray 类的 `.dtype` 是一个 ArrowDtype

Pyarrow 提供了与 NumPy 类似的数组和 数据类型 支持,包括所有数据类型的一等空值支持、不可变性等。

下表显示了 pandas 识别的等效的 pyarrow 支持(pa)、pandas 扩展和 numpy(np)类型。下文中的 pyarrow 支持的类型需要传递给 ArrowDtype 才能被 pandas 识别,例如 pd.ArrowDtype(pa.bool_())

PyArrow 类型

pandas 扩展类型

NumPy 类型

pyarrow.bool_()

BooleanDtype

np.bool_

pyarrow.int8()

Int8Dtype

np.int8

pyarrow.int16()

Int16Dtype

np.int16

pyarrow.int32()

Int32Dtype

np.int32

pyarrow.int64()

Int64Dtype

np.int64

pyarrow.uint8()

UInt8Dtype

np.uint8

pyarrow.uint16()

UInt16Dtype

np.uint16

pyarrow.uint32()

UInt32Dtype

np.uint32

pyarrow.uint64()

UInt64Dtype

np.uint64

pyarrow.float32()

Float32Dtype

np.float32

pyarrow.float64()

Float64Dtype

np.float64

pyarrow.time32()

(无)

(无)

pyarrow.time64()

(无)

(无)

pyarrow.timestamp()

DatetimeTZDtype

np.datetime64

pyarrow.date32()

(无)

(无)

pyarrow.date64()

(无)

(无)

pyarrow.duration()

(无)

np.timedelta64

pyarrow.binary()

(无)

(无)

pyarrow.string()

StringDtype

np.str_

pyarrow.decimal128()

(无)

(无)

pyarrow.list_()

(无)

(无)

pyarrow.map_()

(无)

(无)

pyarrow.dictionary()

CategoricalDtype

(无)

注意

pyarrow 支持的字符串包括 pd.StringDtype("pyarrow")pd.ArrowDtype(pa.string())pd.StringDtype("pyarrow") 在下面的字符串部分进行了描述,如果指定了字符串别名 "string[pyarrow]",则会返回该字符串。 pd.ArrowDtype(pa.string()) 通常与不同类型的 ArrowDtype 具有更好的互操作性。

虽然 arrays.ArrowExtensionArray 中的单个值存储为 PyArrow 对象,但标量会**返回**为与数据类型对应的 Python 标量,例如,PyArrow int64 将返回为 Python int,或者 NA 表示缺失值。

arrays.ArrowExtensionArray(values)

由 PyArrow ChunkedArray 支持的 Pandas ExtensionArray。

ArrowDtype(pyarrow_dtype)

PyArrow 数据类型的 ExtensionDtype。

更多信息,请参阅 PyArrow 用户指南

日期时间#

NumPy 无法原生表示带时区的日期时间。pandas 通过 arrays.DatetimeArray 扩展数组来支持这一点,该数组可以包含时区感知或时区不敏感的值。

Timestamp 是 pandas 的标量类型,用于时区感知或时区不敏感的日期时间数据,它是 datetime.datetime 的子类。NaT 是日期时间数据的缺失值。

Timestamp([ts_input, year, month, day, ...])

Pandas 替换 Python datetime.datetime 对象。

属性#

Timestamp.asm8

返回具有相同精度的 NumPy datetime64 格式。

Timestamp.day

返回 Timestamp 的日期。

Timestamp.dayofweek

返回星期几。

Timestamp.day_of_week

返回星期几。

Timestamp.dayofyear

返回一年中的第几天。

Timestamp.day_of_year

返回一年中的第几天。

Timestamp.days_in_month

返回月份的天数。

Timestamp.daysinmonth

返回月份的天数。

Timestamp.fold

返回 Timestamp 的 fold 值。

Timestamp.hour

返回 Timestamp 的小时。

Timestamp.is_leap_year

如果年份是闰年,则返回 True。

Timestamp.is_month_end

检查日期是否为月份的最后一天。

Timestamp.is_month_start

检查日期是否为月份的第一天。

Timestamp.is_quarter_end

检查日期是否为季度的最后一天。

Timestamp.is_quarter_start

检查日期是否为季度的第一天。

Timestamp.is_year_end

如果日期是该年的最后一天,则返回 True。

Timestamp.is_year_start

如果日期是该年的第一天,则返回 True。

Timestamp.max

Timestamp.microsecond

返回 Timestamp 的微秒。

Timestamp.min

Timestamp.minute

返回 Timestamp 的分钟。

Timestamp.month

返回 Timestamp 的月份。

Timestamp.nanosecond

返回 Timestamp 的纳秒。

Timestamp.quarter

返回 Timestamp 的季度。

Timestamp.resolution

Timestamp.second

返回 Timestamp 的秒。

Timestamp.tz

tzinfo 的别名。

Timestamp.tzinfo

返回 Timestamp 的时区信息。

Timestamp.unit

与 self._creso 相关联的缩写。

Timestamp.value

返回 Timestamp 的值。

Timestamp.week

返回一年中的周数。

Timestamp.weekofyear

返回一年中的周数。

Timestamp.year

返回 Timestamp 的年份。

方法#

Timestamp.as_unit(unit[, round_ok])

将底层的 int64 表示转换为给定的单位。

Timestamp.astimezone(tz)

将带时区 Timestamp 转换为另一个时区。

Timestamp.ceil(freq[, ambiguous, nonexistent])

返回一个向上取整到此分辨率的新 Timestamp。

Timestamp.combine(date, time)

将日期和时间合并为一个 Timestamp 对象。

Timestamp.ctime()

返回一个 ctime() 风格的 Timestamp 字符串。

Timestamp.date()

返回具有相同年、月、日的 datetime.date

Timestamp.day_name([locale])

返回具有指定区域设置的 Timestamp 的星期名称。

Timestamp.dst()

返回夏令时 (DST) 调整。

Timestamp.floor(freq[, ambiguous, nonexistent])

返回一个向下取整到此分辨率的新 Timestamp。

Timestamp.fromordinal(ordinal[, tz])

从前生公历序数构造时间戳。

Timestamp.fromtimestamp(ts[, tz])

从 POSIX 时间戳创建 Timestamp 对象。

Timestamp.isocalendar()

返回一个包含 ISO 年、周数和星期几的命名元组。

Timestamp.isoformat([sep, timespec])

按 ISO 8601 格式化时间。

Timestamp.isoweekday()

返回日期表示的星期几。

Timestamp.month_name([locale])

返回具有指定区域设置的 Timestamp 的月份名称。

Timestamp.normalize()

将 Timestamp 规范化为午夜,保留 tz 信息。

Timestamp.now([tz])

返回表示当前本地时间的新 Timestamp 对象。

Timestamp.replace([year, month, day, hour, ...])

实现 datetime.replace,处理纳秒。

Timestamp.round(freq[, ambiguous, nonexistent])

将 Timestamp 四舍五入到指定的分辨率。

Timestamp.strftime(format)

返回 Timestamp 的格式化字符串。

Timestamp.strptime(date_string, format)

将字符串参数转换为日期时间。

Timestamp.time()

返回具有相同时间但 tzinfo=None 的 time 对象。

Timestamp.timestamp()

返回 POSIX 时间戳(浮点数)。

Timestamp.timetuple()

返回时间元组,与 time.localtime() 兼容。

Timestamp.timetz()

返回具有相同时间和 tzinfo 的 time 对象。

Timestamp.to_datetime64()

返回具有相同精度的 NumPy datetime64 对象。

Timestamp.to_numpy([dtype, copy])

将 Timestamp 转换为 NumPy datetime64。

Timestamp.to_julian_date()

将 Timestamp 转换为儒略日。

Timestamp.to_period([freq])

返回此时间戳是观测值的周期。

Timestamp.to_pydatetime([warn])

将 Timestamp 对象转换为本地 Python datetime 对象。

Timestamp.today([tz])

返回本地时区的当前时间。

Timestamp.toordinal()

返回前生公历序数。

Timestamp.tz_convert(tz)

将带时区 Timestamp 转换为另一个时区。

Timestamp.tz_localize(tz[, ambiguous, ...])

将 Timestamp 本地化到某个时区。

Timestamp.tzname()

返回时区名称。

Timestamp.utcfromtimestamp(ts)

从 POSIX 时间戳构造带时区的 UTC 日期时间。

Timestamp.utcnow()

返回表示 UTC 日期和时间的新 Timestamp。

Timestamp.utcoffset()

返回 UTC 偏移量。

Timestamp.utctimetuple()

返回 UTC 时间元组,与 time.localtime() 兼容。

Timestamp.weekday()

返回日期表示的星期几。

一组时间戳可以存储在 arrays.DatetimeArray 中。对于带时区的数据,arrays.DatetimeArray 的 `.dtype` 是 DatetimeTZDtype。对于时区不敏感的数据,使用 np.dtype("datetime64[ns]")

如果数据是带时区的,那么数组中的每个值都必须具有相同的时区。

arrays.DatetimeArray(data[, dtype, freq, copy])

Pandas ExtensionArray,用于时区不敏感或时区敏感的日期时间数据。

DatetimeTZDtype([unit, tz])

用于带时区日期时间数据的 ExtensionDtype。

时间差#

NumPy 可以原生表示时间差。pandas 提供 Timedelta 以与 Timestamp 对称。NaT 是时间差数据的缺失值。

Timedelta([value, unit])

表示一个持续时间,即两个日期或时间之间的差值。

属性#

Timedelta.asm8

返回一个 NumPy timedelta64 数组标量视图。

Timedelta.components

返回一个类似组件的命名元组。

Timedelta.days

返回时间差的天数。

Timedelta.max

Timedelta.microseconds

返回微秒数(n),其中 0 <= n < 1 毫秒。

Timedelta.min

Timedelta.nanoseconds

返回纳秒数(n),其中 0 <= n < 1 微秒。

Timedelta.resolution

Timedelta.seconds

将时间差的总小时、分钟和秒返回为秒。

Timedelta.unit

返回 Timedelta 对象单位。

Timedelta.value

以纳秒为单位返回 Timedelta 对象的值。

Timedelta.view(dtype)

数组视图兼容性。

方法#

Timedelta.as_unit(unit[, round_ok])

将底层的 int64 表示转换为给定的单位。

Timedelta.ceil(freq)

返回一个向上取整到此分辨率的新 Timedelta。

Timedelta.floor(freq)

返回一个向下取整到此分辨率的新 Timedelta。

Timedelta.isoformat()

将 Timedelta 格式化为 ISO 8601 持续时间。

Timedelta.round(freq)

将 Timedelta 四舍五入到指定的分辨率。

Timedelta.to_pytimedelta()

将 pandas Timedelta 对象转换为 Python 的 datetime.timedelta 对象。

Timedelta.to_timedelta64()

返回精度为“ns”的 numpy.timedelta64 对象。

Timedelta.to_numpy([dtype, copy])

将 Timedelta 转换为 NumPy timedelta64。

Timedelta.total_seconds()

持续时间中的总秒数。

一组 Timedelta 可以存储在 TimedeltaArray 中。

arrays.TimedeltaArray(data[, dtype, freq, copy])

Pandas ExtensionArray,用于 timedelta 数据。

周期#

pandas 使用 Period 对象来表示时间跨度。

Period#

Period([value, freq, ordinal, year, month, ...])

表示一个时间段。

属性#

Period.day

获取 Period 所属月份的日期。

Period.dayofweek

Period 所在周的星期几,周一=0,周日=6。

Period.day_of_week

Period 所在周的星期几,周一=0,周日=6。

Period.dayofyear

返回一年中的第几天。

Period.day_of_year

返回一年中的第几天。

Period.days_in_month

获取此 Period 所属月份的总天数。

Period.daysinmonth

获取此 Period 所属月份的总天数。

Period.end_time

获取 Period 结束时间戳。

Period.freq

返回此 Period 的频率对象。

Period.freqstr

返回频率的字符串表示。

Period.hour

获取 Period 的小时分量。

Period.is_leap_year

如果 Period 所在的年份是闰年,则返回 True。

Period.minute

获取 Period 的分钟分量。

Period.month

返回此 Period 所属的月份。

Period.ordinal

返回此 Period 的整数序数。

Period.quarter

返回此 Period 所属的季度。

Period.qyear

根据其起始季度,Period 所属的财政年度。

Period.second

获取 Period 的秒分量。

Period.start_time

获取 Period 开始时间戳。

Period.week

获取给定 Period 的一年中的周数。

Period.weekday

Period 所在周的星期几,周一=0,周日=6。

Period.weekofyear

获取给定 Period 的一年中的周数。

Period.year

返回此 Period 所属的年份。

方法#

Period.asfreq(freq[, how])

将 Period 转换为所需的频率,在区间的开始或结束处。

Period.now(freq)

返回当前日期的 Period。

Period.strftime(fmt)

返回 Period 的格式化字符串表示。

Period.to_timestamp([freq, how])

返回 Period 的 Timestamp 表示。

Period 的集合可以存储在 arrays.PeriodArray 中。 arrays.PeriodArray 中的每个 Period 必须具有相同的 freq

arrays.PeriodArray(values[, dtype, copy])

用于存储 Period 数据的 Pandas 扩展数组。

PeriodDtype(freq)

Period 数据的扩展数据类型。

区间#

任意区间可以用 Interval 对象表示。

Interval

实现 Interval 的不可变对象,一个类似切片的有界区间。

属性#

Interval.closed

描述区间包含的边的字符串。

Interval.closed_left

检查区间左侧是否包含。

Interval.closed_right

检查区间右侧是否包含。

Interval.is_empty

指示区间是否为空,意味着它不包含任何点。

Interval.left

区间的左边界。

Interval.length

返回区间的长度。

Interval.mid

返回区间的中间点。

Interval.open_left

检查区间左侧是否开放。

Interval.open_right

检查区间右侧是否开放。

Interval.overlaps(other)

检查两个 Interval 对象是否重叠。

Interval.right

区间的右边界。

区间集合可以存储在 arrays.IntervalArray 中。

arrays.IntervalArray(data[, closed, dtype, ...])

用于存储同一侧闭合的区间数据的 Pandas 数组。

IntervalDtype([subtype, closed])

Interval 数据的扩展数据类型。

可空整数#

numpy.ndarray 无法原生表示带有缺失值的整数数据。Pandas 通过 arrays.IntegerArray 提供此功能。

arrays.IntegerArray(values, mask[, copy])

整数(可选缺失)值的数组。

Int8Dtype()

int8 整数数据的扩展数据类型。

Int16Dtype()

int16 整数数据的扩展数据类型。

Int32Dtype()

int32 整数数据的扩展数据类型。

Int64Dtype()

int64 整数数据的扩展数据类型。

UInt8Dtype()

uint8 整数数据的扩展数据类型。

UInt16Dtype()

uint16 整数数据的扩展数据类型。

UInt32Dtype()

uint32 整数数据的扩展数据类型。

UInt64Dtype()

uint64 整数数据的扩展数据类型。

可空浮点数#

arrays.FloatingArray(values, mask[, copy])

浮点数(可选缺失)值的数组。

Float32Dtype()

float32 数据的扩展数据类型。

Float64Dtype()

float64 数据的扩展数据类型。

分类数据#

pandas 定义了一种自定义数据类型,用于表示只能取有限固定值集的数据。 Categorical 的数据类型可以用 CategoricalDtype 来描述。

CategoricalDtype([categories, ordered])

具有类别和排序性的分类数据的类型。

CategoricalDtype.categories

包含允许的唯一类别的 Index

CategoricalDtype.ordered

类别是否具有排序关系。

分类数据可以存储在 pandas.Categorical 中。

Categorical(values[, categories, ordered, ...])

以经典 R / S-plus 的方式表示分类变量。

当您已经有了类别和整数代码时,可以使用替代的 Categorical.from_codes() 构造函数。

Categorical.from_codes(codes[, categories, ...])

根据代码和类别或数据类型创建 Categorical 类型。

数据类型信息可在 Categorical 上获取。

Categorical.dtype

此实例的 CategoricalDtype

Categorical.categories

此分类数据的类别。

Categorical.ordered

类别是否具有排序关系。

Categorical.codes

此分类索引的类别代码。

np.asarray(categorical) 的工作原理是实现数组接口。请注意,这会将 Categorical 转换回 NumPy 数组,因此类别和顺序信息不会被保留!

Categorical.__array__([dtype, copy])

NumPy 数组接口。

Categorical 可以存储在 SeriesDataFrame 中。要创建 dtype 为 category 的 Series,请使用 cat = s.astype(dtype)Series(..., dtype=dtype),其中 dtype 是以下之一:

如果 Series 的 dtype 为 CategoricalDtype,则可以使用 Series.cat 来更改分类数据。更多信息请参阅 Categorical accessor

Categorical 上有更多方法可用。

Categorical.as_ordered()

将 Categorical 设置为有序。

Categorical.as_unordered()

将 Categorical 设置为无序。

Categorical.set_categories(new_categories[, ...])

将类别设置为指定的新类别。

Categorical.rename_categories(new_categories)

重命名类别。

Categorical.reorder_categories(new_categories)

按 new_categories 中指定的顺序重新排列类别。

Categorical.add_categories(new_categories)

添加新类别。

Categorical.remove_categories(removals)

删除指定的类别。

Categorical.remove_unused_categories()

删除未使用的类别。

Categorical.map(mapper[, na_action])

使用输入映射或函数映射类别。

Sparse#

数据中重复单个值(例如 0NaN)很多次,可以高效地存储为 arrays.SparseArray

arrays.SparseArray(data[, sparse_index, ...])

用于存储稀疏数据的扩展数组。

SparseDtype([dtype, fill_value])

存储在 SparseArray 中的数据的数据类型。

如果 Series 包含稀疏值,则可以使用 Series.sparse 访问器来访问稀疏特定属性和方法。更多信息请参阅 Sparse accessor用户指南

字符串#

处理文本数据时,其中每个有效元素是字符串或缺失值,我们推荐使用 StringDtype(别名为 "string")。

arrays.StringArray(values, *[, dtype, copy])

字符串数据的扩展数组。

arrays.ArrowStringArray(values, *[, dtype])

pyarrow.ChunkedArray 存储的字符串数据的扩展数组。

StringDtype([storage, na_value])

字符串数据的扩展数据类型。

对于由 arrays.StringArray 支持的 Series,可以使用 Series.str 访问器。更多信息请参阅 String handling

可空布尔值#

布尔数据类型(别名为 "boolean")提供了支持存储带有缺失值的布尔数据(TrueFalse),这在使用 numpy.ndarray 时是不可能的。

arrays.BooleanArray(values, mask[, copy])

带有缺失值的布尔值(True/False)数据的数组。

BooleanDtype()

布尔数据的扩展数据类型。

实用工具#

构造函数#

api.types.union_categoricals(to_union[, ...])

合并列表状的 Categorical 类,并合并类别。

api.types.infer_dtype(value[, skipna])

返回列表状输入中元素类型的字符串标签。

api.types.pandas_dtype(dtype)

将输入转换为仅 Pandas 的 dtype 对象或 NumPy 的 dtype 对象。

数据类型自省#

api.types.is_any_real_numeric_dtype(arr_or_dtype)

检查提供的数组或 dtype 是否为实数 dtype。

api.types.is_bool_dtype(arr_or_dtype)

检查提供的数组或 dtype 是否为布尔 dtype。

api.types.is_categorical_dtype(arr_or_dtype)

(已弃用) 检查数组状对象或 dtype 是否为 Categorical dtype。

api.types.is_complex_dtype(arr_or_dtype)

检查提供的数组或 dtype 是否为复数 dtype。

api.types.is_datetime64_any_dtype(arr_or_dtype)

检查提供的数组或 dtype 是否为 datetime64 dtype。

api.types.is_datetime64_dtype(arr_or_dtype)

检查数组状对象或 dtype 是否为 datetime64 dtype。

api.types.is_datetime64_ns_dtype(arr_or_dtype)

检查提供的数组或 dtype 是否为 datetime64[ns] dtype。

api.types.is_datetime64tz_dtype(arr_or_dtype)

(已弃用) 检查数组状对象或 dtype 是否为 DatetimeTZDtype dtype。

api.types.is_dtype_equal(source, target)

检查两个 dtype 是否相等。

api.types.is_extension_array_dtype(arr_or_dtype)

检查对象是否为 Pandas 扩展数组类型。

api.types.is_float_dtype(arr_or_dtype)

检查提供的数组或 dtype 是否为浮点数 dtype。

api.types.is_int64_dtype(arr_or_dtype)

(已弃用) 检查提供的数组或 dtype 是否为 int64 dtype。

api.types.is_integer_dtype(arr_or_dtype)

检查提供的数组或 dtype 是否为整数 dtype。

api.types.is_interval_dtype(arr_or_dtype)

(已弃用) 检查数组状对象或 dtype 是否为 Interval dtype。

api.types.is_numeric_dtype(arr_or_dtype)

检查提供的数组或 dtype 是否为数值 dtype。

api.types.is_object_dtype(arr_or_dtype)

检查数组状对象或 dtype 是否为 object dtype。

api.types.is_period_dtype(arr_or_dtype)

(已弃用) 检查数组状对象或 dtype 是否为 Period dtype。

api.types.is_signed_integer_dtype(arr_or_dtype)

检查提供的数组或 dtype 是否为有符号整数 dtype。

api.types.is_string_dtype(arr_or_dtype)

检查提供的数组或 dtype 是否为字符串 dtype。

api.types.is_timedelta64_dtype(arr_or_dtype)

检查数组状对象或 dtype 是否为 timedelta64 dtype。

api.types.is_timedelta64_ns_dtype(arr_or_dtype)

检查提供的数组或 dtype 是否为 timedelta64[ns] dtype。

api.types.is_unsigned_integer_dtype(arr_or_dtype)

检查提供的数组或 dtype 是否为无符号整数 dtype。

api.types.is_sparse(arr)

(已弃用) 检查数组状对象是否为一维 Pandas 稀疏数组。

可迭代对象自省#

api.types.is_dict_like(obj)

检查对象是否为字典类。

api.types.is_file_like(obj)

检查对象是否为文件类对象。

api.types.is_list_like(obj[, allow_sets])

检查对象是否为列表类。

api.types.is_named_tuple(obj)

检查对象是否为命名元组。

api.types.is_iterator(obj)

检查对象是否为迭代器。

标量自省#

api.types.is_bool(obj)

如果给定对象为布尔值,则返回 True。

api.types.is_complex(obj)

如果给定对象为复数,则返回 True。

api.types.is_float(obj)

如果给定对象为浮点数,则返回 True。

api.types.is_hashable(obj[, allow_slice])

如果 hash(obj) 将成功,则返回 True,否则返回 False。

api.types.is_integer(obj)

如果给定对象为整数,则返回 True。

api.types.is_number(obj)

检查对象是否为数字。

api.types.is_re(obj)

检查对象是否为正则表达式模式实例。

api.types.is_re_compilable(obj)

检查对象是否可以编译为正则表达式模式实例。

api.types.is_scalar(val)

如果给定对象为标量,则返回 True。