首页 > 解决方案 > 如何在使用 str.contains pandas 时打印列表中的缺失项

问题描述

我正在从 csv 文件中过滤一些工作正常的数据,但是在通过str.conatinpandas 中的正则表达式匹配列表项时,它会打印找到的项的结果,但我想标记不匹配的项,例如"kpc8472", "kpc1165"这些不存在于CSV 文件因此不返回任何结果,但我需要知道那些丢失的项目也被标记。

import pandas as pd
# server names to be searched on the file in list format    
search_list =  ["kpc2021","kpc8291","kpc8471", "kpc8472", "kpc1165"]

# sorted column list
cols = [ 'Server', 'Server Name', 'iLO FW', 'Firmware', 'Appliance Name']

# Reading CSV with filtered columns
df = pd.read_csv("Server-Inventory.csv", usecols=cols)

# match the search_list items from the column "Server Name"
df = df[df['Server Name'].astype(str).str.contains('|'.join(search_list))]
print(df)

数据框:

           Server                    Server Name            iLO FW                Firmware         Appliance Name
0  ENC2002, bay 10                      kpc2021   2.50 Sep 23 2016  I36 v2.52 (10/25/2020)  OV C7000 enclosures 1
1  ENC8023, bay 7                kpc8291.db.com   2.40 Dec 02 2015  I36 v2.52 (10/25/2020)  OV C7000 enclosures 1
2  enc8009, bay 12                kpc8471.db.com  2.61 Jul 27 2018  I42 v1.42 (06/20/2020)  OV C7000 enclosures 1
3  enc1011, bay 1                        kpc8479  2.55 Aug 16 2017  I36 v2.74 (10/21/2019)  OV C7000 enclosures 1
4  enc1014, bay 1                        kpc1168  2.70 May 07 2019  I36 v2.74 (11/13/2019)  OV C7000 enclosures 1

结果:

               Server Server Name            iLO FW                Firmware         Appliance Name
440   ENC2002, bay 10     kpc2021  2.55 Aug 16 2017  I36 v2.52 (10/25/2020)  OV C7000 enclosures 1
981    enc8023, bay 7     kpc8291  2.55 Aug 16 2017  I36 v2.52 (10/25/2020)  OV C7000 enclosures 2
2642  enc8009, bay 12     kpc8471  1.30 May 31 2018  I42 v1.42 (06/20/2020)                 ov7003

感谢您的帮助和想法。

注意:我需要标记列表search_list中不匹配的项目!

标签: pythonpython-3.xpandas

解决方案


而不是使用.str.contains,使用.str.extractall来准确获取与列表中的项目匹配的子字符串。.isin然后使用(或set逻辑)检查列表中的哪些元素与至少一件事匹配。

pat = '(' + '|'.join(search_list) + ')'
#'(kpc2021|kpc8291|kpc8471|kpc8472|kpc1165)'

result = pd.DataFrame({'item': search_list})
result['in_df'] = result['item'].isin(df['Server Name'].str.extractall(pat)[0])

print(result)

      item  in_df
0  kpc2021   True
1  kpc8291   True
2  kpc8471   True
3  kpc8472  False
4  kpc1165  False

使用.str.extractall我们得到一系列我们匹配的子字符串。有一个 MultiIndex,外层是原始 DataFrame 索引,内层是它在该行匹配的项目数的计数器(.extractall 可以有多个匹配项)。

df['Server Name'].str.extractall(pat)[0]
#   match
#0  0        kpc2021
#1  0        kpc8291
#2  0        kpc8471
#Name: 0, dtype: object

推荐阅读