gpt4 book ai didi

python - Pandas 和应用函数来匹配一个字符串

转载 作者:行者123 更新时间:2023-11-28 22:33:39 24 4
gpt4 key购买 nike

我有一个包含各种链接的 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' object has no attribute 'str'

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

最佳答案

我想你需要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

关于python - Pandas 和应用函数来匹配一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39724182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com