大熊猫如何添加搜索“?”带str。包含

时间:2019-03-29 15:07:43

标签: python-3.x pandas

我正在使用熊猫str.contains来扩展对多个模式的搜索,其中包括"?"运算符,该运算符可以运行并且结果正确。

我想从专家的观点中了解以下几点。

  1. 是否有更好的方法来使用"|",例如将所有 将模式搜索到如下所示的变量中,我知道这是可行的,但想知道是否使用它的更好方法?

    str.contains

  2. 您可能会看到我在某些主机名上出现了patt = "AIX|CentOS|RHEL|SunOS|SuSE|Ubuntu|\?",可以使用熊猫来删除那些主机名,例如*

代码段:

test-centos71*

结果:

$ cat getsurvey.py
#!/usr/bin/python3
import pandas as pd
##### Python pandas, widen output display to see more columns. ####
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)
##################### END OF THE Display Settings ###################

col_names = ['Hostname', 'IP Address', 'Aux Site', 'CPU Model', 'CDN Version', 'OS Version', 'Kernel Version', 'LDAP Profile']
#df1 = pd.read_csv('host.txt-Org', delimiter = "\t", usecols=col_names, encoding='cp1252', low_memory=False)
df1 = pd.read_csv('host.txt-Org', delimiter = "\t", usecols=col_names, encoding='cp1252',  dtype='unicode')
df2 = df1[df1['OS Version'].str.contains("AIX|CentOS|RHEL|SunOS|SuSE|Ubuntu|\?",  na=False)][['Hostname', 'IP Address', 'Aux Site', 'OS Version']]
print(df2)

原始数据:

$ ./getsurvey.py 
                               Hostname        IP Address              Aux Site                 OS Version
5266                     test-centos71*            NaN                    NaN                          ?
9824                      test-centos72     192.1.1.126                  test                          ?
9886                      test-centos73     192.1.1.36                   test                          ?
11457                    test-centos74*     192.1.1.107                  test                          ?
12485                    test-centos75*     192.1.11.85                  test                          ?
13187                         foreman01     192.1.1.31                   test                          ?

感谢您的时间并提供高级帮助。

编辑:

我用替换理解了我的第二个问题的解决方案。这很好,只是开放以征询其他意见..

Hostname    IP Address  Aux Site    CPU Model             CDN Version   OS Version  Kernel Version              LDAP Profile
test-centos71*  NaN         NaN      1x 2.90 GHz Xeon E5-4617    f06.01         RHEL 5.5    2.6.18-194.el5               STD
test-centos72   192.1.1.126 US DC        1x 3.00 GHz Xeon E5-2690    f03.00         RHEL 6.5    2.6.32-431.11.2.el6.x86_6    STD
test-centos76*  NaN         NaN      1x 2.90 GHz Xeon E5-4617    f06.01         RHEL 5.5    2.6.18-194.el5               STD

1 个答案:

答案 0 :(得分:1)

您还可以尝试replace()和re.sub():

df2['Hostname'] = df2['Hostname'].replace('\*', '')

或者

import re
df2['Hostname'] = df2['Hostname'].apply(lambda x: re.sub(r'\*', '', x))
相关问题