在 pandas 中获取列与特定值匹配的行的索引-ag捕鱼王app官网

在 pandas 中获取列与特定值匹配的行的索引

作者:迹忆客 最近更新:2024/04/22 浏览次数:

本文演示了 pandas 中如何获取符合特定条件的行的索引。

在特征工程中,查找行的索引的必要性是很重要的。这些技能对于去除 dataframe 中的离群值或异常值很有用。索引,也就是行标签,可以在 pandas 中使用几个函数找到。在下面的例子中,我们将处理使用以下代码段创建的 dataframe。

import pandas as pd
import numpy as np
np.random.seed(0)
df = pd.dataframe(np.random.randint(1, 20, size=(20, 4)), columns=list("abcd"))
print(df)

输出:

     a   b   c   d
0   13  16   1   4
1    4   8  10  19
2    5   7  13   2
3    7   8  15  18
4    6  14   9  10
5   17   6  16  16
6    1  19   4  18
7   15   8   1   2
8   10   1  11   4
9   12  19   3   1
10   1   5   6   7
11   9  18  16   5
12  10  11   2   2
13   8  10   4   7
14  12  15  19   1
15  15   4  13  11
16  12   5   7   5
17  16   4  13   5
18   9  15  16   4
19  16  14  17  18

在 pandas 中获取包含整数/浮点数的行的索引

pandas.dataframe.loc 函数可以通过其标签/名称访问行和列。它直接返回与作为标签传递的给定布尔条件相匹配的行。请注意片段中 df.loc 旁边的方括号。

import pandas as pd
import numpy as np
np.random.seed(0)
df = pd.dataframe(np.random.randint(1, 20, size=(20, 4)), columns=list("abcd"))
print(df.loc[df["b"] == 19])

对应于布尔条件的行将以 dataframe 格式的输出返回。

输出:

    a   b  c   d
6   1  19  4  18
9  12  19  3   1

多个条件可以被串联起来并一起应用到函数中,如下所示。这有助于根据特定条件隔离行。

import pandas as pd
import numpy as np
np.random.seed(0)
df = pd.dataframe(np.random.randint(1, 20, size=(20, 4)), columns=list("abcd"))
print(df.loc[(df["b"] == 19) | (df["c"] == 19)])

输出:

     a   b   c   d
6    1  19   4  18
9   12  19   3   1
14  12  15  19   1

pandas.dataframe.index() 获取行的索引

如果你想只查找满足作为参数传递的布尔条件的 dataframe 的匹配索引,pandas.dataframe.index() 是最简单的实现方式。

import pandas as pd
import numpy as np
np.random.seed(0)
df = pd.dataframe(np.random.randint(1, 20, size=(20, 4)), columns=list("abcd"))
print(df.index[df["b"] == 19].tolist())

在上面的代码段中,列 a 中与布尔条件 == 1 相匹配的行以输出的方式返回,如下所示。

输出:

[6, 9]

我们之所以把 tolist() 放在 index() 方法后面,是为了把 index 转换为列表,否则,结果就是 int64index 数据类型。

int64index([6, 9], dtype='int64'

也可以根据多个条件只检索索引。这段代码可以写成如下。

import pandas as pd
import numpy as np
np.random.seed(0)
df = pd.dataframe(np.random.randint(1, 20, size=(20, 4)), columns=list("abcd"))
print(df.index[(df["b"] == 19) | (df["c"] == 19)].tolist())

输出:

[6, 9, 14]

在 pandas 中获取包含字符串的行的索引

字符串值可以根据两种方法进行匹配。上一节中所示的两种方法都可以使用,除了条件变化。

在下面的例子中,我们将使用以下片段。

import pandas as pd
df = pd.dataframe(
    {
        "name": ["blue", "delta", "echo", "charlie", "alpha"],
        "type": ["raptors", "raptors", "raptors", "raptors", "tyrannosaurus rex"],
    }
)
print(df)

输出:

      name               type
0     blue            raptors
1    delta            raptors
2     echo            raptors
3  charlie            raptors
4    alpha  tyrannosaurus rex

用精确字符串匹配获取行的索引

上一节中使用的相等条件可以用来寻找 dataframe 中的精确字符串匹配。我们来寻找两个字符串。

import pandas as pd
df = pd.dataframe(
    {
        "name": ["blue", "delta", "echo", "charlie", "alpha"],
        "type": ["raptors", "raptors", "raptors", "raptors", "tyrannosaurus rex"],
    }
)
print(df.index[(df["name"] == "blue")].tolist())
print("\n")
print(df.loc[df["name"] == "blue"])
print("\n")
print(df.loc[(df["name"] == "charlie") & (df["type"] == "raptors")])

输出:

[0]
   name     type
0  blue  raptors
      name     type
3  charlie  raptors

如上所示,索引和符合条件的行都可以被接收。

获取具有部分字符串匹配条件的行的索引

通过将 dataframe 与 str.contains 函数进行链式连接,可以部分匹配字符串值。在下面的例子中,我们将在 charlie 和 alpha中寻找字符串 ha

import pandas as pd
df = pd.dataframe(
    {
        "name": ["blue", "delta", "echo", "charlie", "alpha"],
        "type": ["raptors", "raptors", "raptors", "raptors", "tyrannosaurus rex"],
    }
)
print(df.index[df["name"].str.contains("ha")].tolist())
print("\n")
print(df.loc[df["name"].str.contains("ha")])
print("\n")
print(df.loc[(df["name"].str.contains("ha")) & (df["type"].str.contains("rex"))])

输出:

[3, 4]
      name               type
3  charlie            raptors
4    alpha  tyrannosaurus rex
    name               type
4  alpha  tyrannosaurus rex

这个函数在对 dataframe 的多列进行部分字符串匹配时非常有用。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:python

pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 dataframe 中。

pandas 追加数据到 csv 中

发布时间:2024/04/24 浏览次数:352 分类:python

本教程演示了如何在追加模式下使用 to_csv()向现有的 csv 文件添加数据。

pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:python

本教程介绍了如何在 pandas 中使用 dataframe.merge()方法合并两个 dataframes。

pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:python

本教程介绍了如何使用 python 中的 loc 和 iloc 从 pandas dataframe 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便
网站地图