如何在使用str.contains时打印缺少的列表项

2024-09-22 16:37:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从csv文件中筛选一些数据,效果很好,但在通过pandas中的str.conatinregex匹配列表项时,它会打印找到的项的结果,但我想标记不匹配的项,如"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中不匹配的项目


Tags: csvthename标记dfsearchserverlist
3条回答

与其使用.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我们得到一系列匹配的子字符串。有一个多索引,外部级别是原始数据帧索引,内部级别是它在该行上匹配的项数的计数器(.extractall可以有多个匹配项)

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

要返回不匹配项,请添加~

df = df[~df['Server Name'].astype(str).str.contains('|'.join(search_list))]

我认为您可以通过比较两个列表来尝试:

serverName_list=df['Server Name'].unique().tolist()

如果“服务器名称”列的所有元素都具有相同的格式,则应使用以下内容清理数据,例如:

serverName_clean_list=[] 
for element in serverName_list:
    serverName_clean_list.append(element.split(".")[0])

根据Python find elements in one list that are not in the other

import numpy as np
main_list = np.setdiff1d(serverName_clean_list, search_list).tolist()
# yields the elements in `list_2` that are NOT in `list_1`

相关问题 更多 >