pandas获取dataframe行数列数
时间: 2025-02-01 16:13:08 浏览: 91
### 使用 Pandas 获取 DataFrame 的行数和列数
为了获取 Pandas DataFrame 中的行数和列数,可以采用多种方法。
#### 方法一:使用 `shape` 属性
这是最常用的方法之一。通过访问 `DataFrame.shape` 可以得到一个包含两个元素的元组,第一个元素表示行数,第二个元素表示列数[^2]。
```python
import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]
})
print(f"行数: {df.shape[0]}") # 行数
print(f"列数: {df.shape[1]}") # 列数
```
#### 方法二:使用 `len()` 函数与 `columns` 属性组合
另一种方式是利用 Python 内置函数 `len()` 来计算行数,并结合 `DataFrame.columns` 访问器来统计列的数量[^1]。
```python
row_count = len(df) # 行数
column_count = len(df.columns) # 列数
print(f"行数: {row_count}")
print(f"列数: {column_count}")
```
这两种方法都能有效地帮助用户了解数据集的基本结构信息,在实际应用中可根据个人习惯选择合适的方式。
相关问题
DataFrame行数列数
DataFrame的行数可以用`.shape[0]`来获取,列数可以用`.shape[1]`来获取。例如:
``` python
import pandas as pd
# 创建一个DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
# 获取行数和列数
num_rows = df.shape[0]
num_cols = df.shape[1]
print(f'行数:{num_rows}')
print(f'列数:{num_cols}')
```
输出结果为:
```
行数:3
列数:2
```
pandas dataframe获取行数
### 获取 Pandas DataFrame 行数的方法
在 Pandas 中,有多种方法可以用来获取 DataFrame 的行数。以下是几种常见的实现方式:
#### 方法一:使用 `len()` 函数
`len()` 是 Python 内置函数之一,可以直接作用于 DataFrame 对象以返回其行数[^3]。
```python
row_count = len(df)
print(row_count)
```
#### 方法二:利用 `.shape` 属性
`.shape` 返回的是一个包含两个元素的元组 (rows, columns),其中第一个元素表示行数,第二个元素表示列数[^2]。因此可以通过索引来提取行数:
```python
row_count = df.shape[0]
print(row_count)
```
#### 方法三:基于索引长度计算
通过访问 DataFrame 的索引属性 (`df.index`) 并对其应用 `len()` 函数也可以得出总行数[^3]:
```python
row_count = len(df.index)
print(row_count)
```
以上三种方法均能有效统计给定 DataFrame 的实际行数量。
### 示例代码综合展示
下面给出一段完整的示例程序,演示前述提到的不同技术手段来取得相同的结果——即目标 DataFrame 的行数目:
```python
import pandas as pd
import numpy as np
# 创建测试用DataFrame
df = pd.DataFrame({'a': [None, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]})
print("原始数据:")
print(df)
# 使用不同方法获取行数
method_one_result = len(df)
method_two_result = df.shape[0]
method_three_result = len(df.index)
# 输出结果对比验证一致性
print(f"\nMethod One Result: {method_one_result}")
print(f"Method Two Result: {method_two_result}")
print(f"Method Three Result: {method_three_result}")
assert method_one_result == method_two_result == method_three_result, "各方法所得行数值不一致"
```
阅读全文
相关推荐
















