📜  pandas df 行数 - Python (1)

📅  最后修改于: 2023-12-03 15:18:13.760000             🧑  作者: Mango

主题:pandas df 行数 - Python

介绍

在 Python 中,pandas 是一个非常流行的数据处理库。pandas 中最基本的数据结构是 DataFrame(简称 df),它类似于 Excel 表格或数据库表。有时我们需要知道 DataFrame 中有多少行数据,这个指南将向你展示如何使用 pandas 来获取 DataFrame 中的行数。

代码示例

首先,让我们导入 pandas 库并创建一个简单的 DataFrame 示例:

import pandas as pd

# 创建 DataFrame
data = {'列1': [1, 2, 3, 4, 5],
        '列2': ['A', 'B', 'C', 'D', 'E'],
        '列3': [True, False, True, False, True]}
df = pd.DataFrame(data)

# 显示 DataFrame
df

| | 列1 | 列2 | 列3 | |---:|----:|----:|:-----| | 0 | 1 | 'A' | True | | 1 | 2 | 'B' | False| | 2 | 3 | 'C' | True | | 3 | 4 | 'D' | False| | 4 | 5 | 'E' | True |

要获取 DataFrame 的行数,可以使用 len() 函数,或者使用 .shape.count() 属性。

# 使用 len() 函数
row_count = len(df)
print("行数(使用 len() 函数):", row_count)

# 使用 .shape 属性
row_count = df.shape[0]  # 获取第一个元素,即行数
print("行数(使用 .shape 属性):", row_count)

# 使用 .count() 属性
row_count = df.count().iloc[0]  # 获取第一个元素,即行数
print("行数(使用 .count() 属性):", row_count)

行数(使用 len() 函数): 5
行数(使用 .shape 属性): 5
行数(使用 .count() 属性): 5

上述三种方法都可以获取到 DataFrame 的行数。其中,.shape 返回一个包含两个元素的元组,第一个元素是行数,第二个元素是列数。.count() 返回一个包含每一列非缺失值数量的 Series 对象。通过取第一个元素,我们可以获取到行数。

结论

通过本指南,你学会了如何使用 pandas 中的三种方法来获取 DataFrame 的行数。你可以根据自己的需要选择其中的一种方法来完成任务。pandas 在数据处理和分析方面有很多其他功能,掌握这些技术能够使你更有效地处理和操作数据。