pandas series.filter() 方法有什么作用?

pandas 系列构造函数中的方法用于根据索引标签对系列对象的行进行子集化。filter 方法不适用于系列对象的内容,它仅适用于系列对象的索引标签。series.filter()

如果指定的标签与系列索引标签不匹配,该方法不会引发错误。

该filter()方法的参数是项目,例如,正则表达式和轴。items 参数采用类似列表的对象来访问给定系列对象的行集。regex 参数用于定义可用于检索系列行的正则表达式。

示例 1

在以下示例中,我们将通过为filter()方法指定索引标签列表来过滤掉 pandas 系列对象中的一些行。

# importing pandas package

import pandas as pd

# creating pandas Series object

series = pd.Series({'B':'black','Y':'yellow', 'W':'white','R':'red', 'Bl':'blue','G':'green','S':"silver", 'M':"maroon"})

print("原创系列:")

print(series)

print("Output: ")

# Apply the filter method

print(series.filter(['B','R','G','M']))

解释

最初,我们使用带有键和值对的 python 字典创建了一个系列对象。在这里,索引标签是使用字典的键创建的。

输出结果

输出如下 -

原创系列:

B    black

Y    yellow

W    white

R    red

Bl    blue

G    green

S    silver

M    maroon

dtype: object

Output:

B    black

R    red

G    green

M    maroon

dtype: object

我们已经成功地从初始系列对象中过滤了指定的行。结果系列对象与输入系列对象具有相同的数据类型。

示例 2

让我们使用另一个系列对象使用索引标签过滤单行,我们必须将单个标签值作为可迭代对象的元素提及,否则会出错。

# importing pandas package

import pandas as pd

# creating pandas Series object

series = pd.Series({1:'East',2:'West',3:'North',4:'South',5:'East',6:'West',7:'North'})

print("原创系列:")

print(series)

print("Output: ")

# Apply the filter method

print(series.filter([2]))

输出结果

输出如下 -

原创系列:

1    East

2    West

3    North

4    South

5    East

6    West

7    North

dtype: object

Output:

2    West

dtype: object

正如我们在上面的输出块中看到的,我们已经成功地从系列对象中过滤了一个行标签。

以上是 pandas series.filter() 方法有什么作用? 的全部内容, 来源链接: utcz.com/z/297253.html

回到顶部