dataframe读取索引数目
时间: 2025-02-08 10:06:19 浏览: 26
### 如何获取Pandas DataFrame中的索引数量
为了获得Pandas DataFrame中索引的数量,可以利用`shape`属性或者`index`对象的长度来实现。以下是两种方法的具体介绍:
#### 利用 `shape` 属性
`shape` 返回的是一个表示DataFrame维度大小的元组 (行数, 列数),其中第一个元素即代表了索引(行)的数量。
```python
import pandas as pd
data = {'Product': ['Computer', 'Printer', 'Monitor', 'Desk', 'Phone', 'Tablet', 'Scanner'],
'Price': [1100, 150, 500, 350, 100, 300, 120]}
df = pd.DataFrame(data)
rows_count = df.shape[0]
print(f"The number of indices is {rows_count}.")
```
此段代码展示了如何通过访问`shape`的第一个元素得到索引总数[^3]。
#### 访问 `index` 对象并计算其长度
另一种方式是直接调用`len()`函数作用于DataFrame的`index`属性上,这同样能够返回索引条目的数目。
```python
indices_length = len(df.index)
print(f"There are {indices_length} items in the index.")
```
这种方法提供了另一种途径去统计索引项的数量[^4]。
阅读全文
相关推荐

















