python - 我们可以在熊猫数据框中使用通配符吗
问题描述
我有下面的代码,但它UserWarning
在打印数据时抛出了一些..
import pandas as pd
pd.set_option('display.height', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('expand_frame_repr', True)
data = pd.read_csv('/home/karn/plura/Test/Python_Pnada/Cyber_July.csv', usecols=['Platform ID', 'Safe', 'Target system address', 'Failure reason'])
hostData = data[data['Platform ID'].str.startswith("CS-Unix-")][data['Safe'].str.startswith("CS-NOI-DEFAULT-UNIX-ROOT")] [['Platform ID', 'Safe', 'Target system address','Failure reason']]
hostData.reset_index(level=0, drop=True)
print(hostData)
下面是用户警告 ..
./CyberCSV.py:12: UserWarning: Boolean Series key will be reindexed to match DataFrame index.
hostData = data[data['Platform ID'].str.startswith("CS-Unix-")][data['Safe'].str.startswith("CS-NOI-DEFAULT-UNIX-ROOT")] [['Platform ID', 'Safe', 'Target system address','Failure reason']]
其次,有没有办法像我一样在数据框中使用通配符
data['Safe'].str.startswith("CDS-NOI-DEFAULT-UNIX-ROOT")
我想用的地方data['Safe'].str.startswith("CDS-*DEFAULT-UNIX-ROOT")
这可能吗。
解决方案
您可以链接startswith
和endswith
掩码或使用contains
-^
用于匹配字符串的开头,.*
用于任何字符串并$
用于结尾:
mask = data['Safe'].str.startswith("CDS") & data['Safe'].str.endswith("DEFAULT-UNIX-ROOT")
或正则表达式:
mask = data['Safe'].str.contains("^CDS-.*DEFAULT-UNIX-ROOT$")
样品:
data = pd.DataFrame({'Safe':['CDS-DEFAULT-UNIX-ROOT',
'CDS-NhjghOI-DEFAULT-UNIX-ROOT',
'CDS-NhjghOI-DEFAULT',
'ACDS-DEFAULT-UNIX-ROOT']})
print (data)
Safe
0 CDS-DEFAULT-UNIX-ROOT
1 CDS-NhjghOI-DEFAULT-UNIX-ROOT
2 CDS-NhjghOI-DEFAULT
3 ACDS-DEFAULT-UNIX-ROOT
mask = data['Safe'].str.contains("^CDS-.*DEFAULT-UNIX-ROOT$")
print (mask)
0 True
1 True
2 False
3 False
Name: Safe, dtype: bool