【Pandas】pandas Index objects Index.shape
Pandas2.2 Index objects
Properties
方法 | 描述 |
---|---|
Index.values | 返回 Index 对象的值,通常是一个 NumPy 数组 |
Index.is_monotonic_increasing | 用于检查索引的元素是否 单调递增 |
Index.is_monotonic_decreasing | 用于判断索引的值是否 单调递减 |
Index.is_unique | 用于检查索引中的标签是否 唯一 |
Index.has_duplicates | 用于检查索引是否包含重复值 |
Index.hasnans | 用于检查索引中是否包含缺失值(NaN) |
Index.dtype | 用于获取索引中元素的数据类型(dtype) |
Index.inferred_type | 用于推断索引中数据的类型 |
Index.shape | 用于返回索引的形状(即索引中元素的数量) |
pandas.Index.shape
pandas.Index.shape
是 pandas.Index
对象的一个属性,用于返回索引的形状(即索引中元素的数量)。它返回一个表示维度大小的元组,对于一维索引来说,返回的是一个单元素元组 (n,)
,其中 n
表示索引的长度。
详细说明:
- 用途:获取索引对象的大小,常用于检查数据结构或进行调试。
- 返回值:一个元组,表示索引的维度。对于一维索引,返回
(n,)
,其中n
是索引的元素个数。
示例代码:
import pandas as pd# 创建一个 Index 对象
index = pd.Index(['A', 'B', 'C', 'D'])# 获取 shape
print(index.shape)
输出结果:
(4,)
示例说明:
在上面的示例中,我们创建了一个包含 4 个元素的 Index
对象,因此 shape
返回 (4,)
,表示该索引有 4 个元素。
其他常见情况:
-
时间序列索引(DatetimeIndex):
index = pd.date_range('20230101', periods=5) print(index.shape) # 输出: (5,)
-
多级索引(MultiIndex):
arrays = [['A', 'A', 'B'], ['1', '2', '3']] index = pd.MultiIndex.from_arrays(arrays) print(index.shape) # 输出: (3,)
总结:shape
常用于快速查看索引对象的大小,返回的是一个元组,其中仅包含一个元素,表示索引的长度。