我正在从csv文件中筛选一些数据,效果很好,但在通过pandas中的str.conatin
regex匹配列表项时,它会打印找到的项的结果,但我想标记不匹配的项,如"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
中不匹配的项目
与其使用
.str.contains
,不如使用.str.extractall
精确地获取与列表中的项目匹配的子字符串。然后使用.isin
(或set
逻辑)检查列表中的哪些元素与至少一个内容匹配使用
.str.extractall
我们得到一系列匹配的子字符串。有一个多索引,外部级别是原始数据帧索引,内部级别是它在该行上匹配的项数的计数器(.extractall可以有多个匹配项)要返回不匹配项,请添加
~
:我认为您可以通过比较两个列表来尝试:
如果“服务器名称”列的所有元素都具有相同的格式,则应使用以下内容清理数据,例如:
根据Python find elements in one list that are not in the other
相关问题 更多 >
编程相关推荐