Python:Slice/transformurl获取项目和项目计数

2024-10-01 05:03:32 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有列数据,例如100个条目属于两种格式;在列名URL下:

http//mysportswebsite.com/shop/?Baseball+Bat=5

http//memoribilia.com/checkout?autograph=1

如何提取购买的商品和编号?你知道吗

理想情况下,我想添加新的列(如果它们还不存在)在这个例子棒球棒和签名,然后添加各自的计数5和1到他们的列(或只是添加到列,如果他们存在从前面的例子),从这个数据推断购买计数。你知道吗

我想对python中的整个URL列执行此操作


Tags: 数据comhttpurl格式条目shop例子
3条回答

对于这个问题(信息有限),我建议:

如果您的df如下所示:

df = pd.DataFrame(data={"url": ["http//mysportswebsite.com/shop/?Baseball+Bat=5", "http//memoribilia.com/checkout?autograph=1"]})

                                              url
0  http//mysportswebsite.com/shop/?Baseball+Bat=5
1      http//memoribilia.com/checkout?autograph=1

你可以这样做:

df['product_count_tuple'] = df.url.apply(lambda x: x.split('?')[1].split('='))
df['product'] = df.product_count_tuple.apply(lambda x: x[0].replace('+', ' '))
df['count'] = df.product_count_tuple.apply(lambda x: x[1])
df = df.drop('product_count_tuple', 1)

结果是:

                                              url       product count
0  http//mysportswebsite.com/shop/?Baseball+Bat=5  Baseball Bat     5
1      http//memoribilia.com/checkout?autograph=1     autograph     1

下面是另一种使用re模块的方法:

import re
df['item'] = df['URL'].apply(lambda x: (re.findall('\?(.*)=', x)[0]).replace('+', ' '))
df['count'] = df['URL'].apply(lambda x: int((re.findall('=(.*)', x)[0])))

Python已经有了解析url的库。你知道吗

>>> import urllib.parse as urlparse
>>> url = 'http//mysportswebsite.com/shop/?Baseball+Bat=5'
>>> parsed_url = urlparse.urlparse(url)
>>> params = urlparse.parse_qs(parsed_url.query)
>>> print(params)
{'Baseball Bat': ['5']}

相关问题 更多 >