pandas获取行数
在使用 pandas 进行数据分析和处理的过程中,我们经常需要获取 DataFrame 或 Series 中的行数。pandas 提供了多种方法来实现这个目标,本文将详细介绍这些方法,并给出相关示例代码。
一、使用shape
属性获取行数
pandas 中的 DataFrame 和 Series 都有一个shape
属性,该属性可以返回对象的维度信息。对于 DataFrame 来说,shape
属性是一个包含行数和列数的元组。通过取元组的第一个元素,我们可以获取 DataFrame 的行数;对于 Series 来说,shape
属性只返回一个包含元素个数的整数。
下面是一些示例代码,演示如何使用shape
属性获取 DataFrame 和 Series 的行数:
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({'A': [1, 2, 3, 4, 5],
'B': [6, 7, 8, 9, 10],
'C': [11, 12, 13, 14, 15]})
# 获取 DataFrame 的行数
rows = df.shape[0]
print(f"DataFrame 的行数为: {rows}")
# 创建一个 Series
s = pd.Series([1, 2, 3, 4, 5])
# 获取 Series 的行数
rows = s.shape[0]
print(f"Series 的行数为: {rows}")
运行结果:
DataFrame 的行数为: 5
Series 的行数为: 5
上述代码中,我们首先创建了一个包含三列的 DataFrame,并给每列添加了五个元素。然后通过shape[0]
来获取 DataFrame 的行数,并通过shape[0]
来获取 Series 的行数。
二、使用len
函数获取行数
除了使用shape
属性,我们还可以使用len
函数来获取 DataFrame 和 Series 的行数。对于 DataFrame 来说,len
函数返回的是 DataFrame 的行数;对于 Series 来说,len
函数返回的是 Series 的元素个数。
下面是一些示例代码,演示如何使用len
函数获取 DataFrame 和 Series 的行数:
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({'A': [1, 2, 3, 4, 5],
'B': [6, 7, 8, 9, 10],
'C': [11, 12, 13, 14, 15]})
# 获取 DataFrame 的行数
rows = len(df)
print(f"DataFrame 的行数为: {rows}")
# 创建一个 Series
s = pd.Series([1, 2, 3, 4, 5])
# 获取 Series 的行数
rows = len(s)
print(f"Series 的行数为: {rows}")
运行结果:
DataFrame 的行数为: 5
Series 的行数为: 5
上述代码中,我们同样先创建了一个包含三列的 DataFrame,并给每列添加了五个元素。然后通过len(df)
来获取 DataFrame 的行数,并通过len(s)
来获取 Series 的行数。
需要注意的是,当使用len
函数获取 DataFrame 的行数时,它返回的是 DataFrame 中的行数,而不是列数。这在一些特殊情况下可能会引起错误的结果。
三、使用index
属性获取行数
在 pandas 中,DataFrame 和 Series 都有一个index
属性,该属性可以返回对象的索引信息。对于 DataFrame 来说,index
属性是一个包含所有行索引的对象;对于 Series 来说,index
属性是一个包含所有元素索引的对象。我们可以通过获取index
属性的长度来获得 DataFrame 或 Series 的行数。
下面是一些示例代码,演示如何使用index
属性获取 DataFrame 和 Series 的行数:
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({'A': [1, 2, 3, 4, 5],
'B': [6, 7, 8, 9, 10],
'C': [11, 12, 13, 14, 15]})
# 获取 DataFrame 的行数
rows = len(df.index)
print(f"DataFrame 的行数为: {rows}")
# 创建一个 Series
s = pd.Series([1, 2, 3, 4, 5])
# 获取 Series 的行数
rows = len(s.index)
print(f"Series 的行数为: {rows}")
运行结果:
DataFrame 的行数为: 5
Series 的行数为: 5
上述代码中,我们同样创建了一个包含三列的 DataFrame,并给每列添加了五个元素。然后通过len(df.index)
来获取 DataFrame 的行数,并通过len(s.index)
来获取 Series 的行数。
需要注意的是,当获取 DataFrame 或 Series 的索引时,我们可以使用index
属性,也可以使用df.index
或s.index
。它们是等价的,可以根据个人喜好来选择使用哪种方式。
综上所述,本文介绍了三种常用的方法来获取 pandas 中 DataFrame 和 Series 的行数,包括使用shape
属性、len
函数和index
属性。这些方法都是简单易用的,根据实际情况选择合适的方法即可。