【问题标题】:Pandas and apply function to match a stringPandas 和应用函数来匹配字符串
【发布时间】:2017-02-05 01:22:16
【问题描述】:

我有一个包含各种链接的 df 列,其中一些包含字符串 "search"

我想创建一个函数 - 应用于列 - 返回包含 "search""other" 的列。

我写了这样一个函数:

search = 'search'
def page_type(x):
if x.str.contains(search):
    return 'Search'
else:
    return 'Other'   

df['link'].apply(page_type)

但它给了我这样的错误:

AttributeError: 'unicode' 对象没有属性 'str'

我想我在调用 str.contains() 时遗漏了一些东西。

【问题讨论】:

    标签: python string pandas conditional-statements contains


    【解决方案1】:

    我觉得你需要numpy.where:

    df = pd.DataFrame({'link':['search','homepage d','login dd', 'profile t', 'ff']})
    
    print (df)
             link
    0      search
    1  homepage d
    2    login dd
    3   profile t
    4          ff
    
    search = 'search'
    profile = 'profile'
    homepage = 'homepage'
    login = "login"
    
    def page_type(x):
        if search in x:
            return 'Search'
        elif profile in x:
            return 'Profile'
        elif homepage in x:
            return 'Homepage'
        elif login in x:
            return 'Login'
        else:
            return 'Other'  
    
    df['link_new'] = df['link'].apply(page_type)
    
    df['link_type'] = np.where(df.link.str.contains(search),'Search', 
                      np.where(df.link.str.contains(profile),'Profile', 
                      np.where(df.link.str.contains(homepage), 'Homepage', 
                      np.where(df.link.str.contains(login),'Login','Other')))) 
    
    
    print (df)
             link  link_new link_type
    0      search    Search    Search
    1  homepage d  Homepage  Homepage
    2    login dd     Login     Login
    3   profile t   Profile   Profile
    4          ff     Other     Other
    

    时间安排

    #[5000 rows x 1 columns]
    df = pd.DataFrame({'link':['search','homepage d','login dd', 'profile t', 'ff']})
    df = pd.concat([df]*1000).reset_index(drop=True)
    
    In [346]: %timeit df['link'].apply(page_type)
    1000 loops, best of 3: 1.72 ms per loop
    
    In [347]: %timeit np.where(df.link.str.contains(search),'Search', np.where(df.link.str.contains(profile),'Profile', np.where(df.link.str.contains(homepage), 'Homepage', np.where(df.link.str.contains(login),'Login','Other'))))
    100 loops, best of 3: 11.7 ms per loop
    

    【讨论】:

    • 我为多个条件添加解决方案,apply 解决方案比np.where 更快。
    【解决方案2】:

    .str 适用于整个系列,但在这里您处理的是系列内的值。

    您可以这样做:df['link'].str.contains(search)
    或者你想要的:df['link'].apply(lambda x: 'Search' if search in x else 'Other')

    编辑

    更通用的方式:

    def my_filter(x, val, c_1, c_2):
        return c_1 if val in x else  c_2 
    
    df['link'].apply(lambda x: my_filter(x, 'homepage', 'homepage', 'other'))
    

    【讨论】:

    • 如果我想指定一个 elif 条件:if homepage then "homepage else 'other'?
    • 这样解决了:df['link_type'] = np.where(df.referrer.str.contains(search),'Search', np.where(df.referrer.str.contains( profile),'Profile', np.where(df.referrer.str.contains(homepage), 'Homepage', np.where(df.referrer.str.contains(login),'Login','Other')) ))
    【解决方案3】:

    如果您想在链接中查找单词搜索,也可以使用list comprehesion

    例如:

    df['Search'] = [('search' if 'search' in item else 'other') for item in df['link']]
    

    输出:

      ColumnA                       link  Search
    0       a        http://word/12/word   other
    1       b     https://search-125.php  search
    2       c      http://news-8282.html   other
    3       d http://search-hello-1.html  search
    

    创建函数:

    def page_type(x, y):
        df[x] = [('search' if 'search' in item else 'other') for item in df[y]]
    
    page_type('Search', 'link')
    
    In [6]: df
    Out[6]:
      ColumnA                        link  Search
    0       a         http://word/12/word   other
    1       b      https://search-125.php  search
    2       c       http://news-8282.html   other
    3       d  http://search-hello-1.html  search 
    

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 2017-07-15
      • 2021-03-07
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      相关资源
      最近更新 更多