我有一个熊猫df,列为url
。数据如下:
row url
1 'https://www.delish.com/cooking/recipe-ideas/recipes/four-cheese'
2 'https://www.delish.com/holiday-recipes/thanksgiving/thanksgiving-cabbage/
3 'https://www.delish.com/kitchen-tools/cookware-reviews/advice/kitchen-tools-gadgets/'
我只需要获取第二个索引的值,即烹饪或节日食谱等。
所需输出:
row url
1 cooking
2 holiday-recipes
3 kitchen-tools
我想把url解析成不同的列,然后去掉我不需要的列。这是代码:
df['protocol'],df['domain'],df['path']=zip(*df['url'].map(urlparse(df['url']).urlsplit))
错误消息为:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
有更好的方法来解决这个问题吗?如何获取特定索引?
这就是您想要的吗?
df['url'] = df['url'].str.split('/').str[3]
print(df)
row url
0 1 cooking
1 2 holiday-recipes
2 3 kitchen-tools
另一种方法是将alphas
与紧接在com
之后的字符-
进行匹配
df['url']=df['url'].str.extract('((?<=com/)[a-z-]+)')
url
0 cooking
1 holiday-recipes
2 kitchen-tools