gpt4 book ai didi

python - 如何在 Python 中仅提取 url 的特定部分并将其值添加为 df 中每一行的另一列?

转载 作者:行者123 更新时间:2023-11-28 21:35:36 26 4
gpt4 key购买 nike

我有一个包含用户和 url 的 df,看起来像这样。

df

User Url
1 http://www.mycompany.com/Overview/Get
2 http://www.mycompany.com/News
3 http://www.mycompany.com/Accountinfo
4 http://www.mycompany.com/Personalinformation/Index
...

我想添加另一个只包含 url 的第二部分的栏目页面,所以我会像这样。

user      url                                                  page
1 http://www.mycompany.com/Overview/Get Overview
2 http://www.mycompany.com/News News
3 http://www.mycompany.com/Accountinfo Accountinfo
4 http://www.mycompany.com/Personalinformation/Index Personalinformation
...

我下面的代码不工作。

slashparts = df['url'].split('/')
df['page'] = slashparts[4]

我得到的错误

  AttributeError                            Traceback (most recent call last)
<ipython-input-23-0350a98a788c> in <module>()
----> 1 slashparts = df['request_url'].split('/')
2 df['page'] = slashparts[1]

~\Anaconda\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
4370 if
self._info_axis._can_hold_identifiers_and_holds_name(name):
4371 return self[name]
-> 4372 return object.__getattribute__(self, name)
4373
4374 def __setattr__(self, name, value):

AttributeError: 'Series' object has no attribute 'split'

最佳答案

使用 Pandas text functions使用 str 并选择 4. 列表使用 str[3],因为 python 从 0 开始计数:

df['page'] = df['Url'].str.split('/').str[3]

或者如果性能很重要,请使用列表理解:

df['page'] = [x.split('/')[3] for x in df['Url']]

print (df)
User Url \
0 1 http://www.mycompany.com/Overview/Get
1 2 http://www.mycompany.com/News
2 3 http://www.mycompany.com/Accountinfo
3 4 http://www.mycompany.com/Personalinformation/I...

page
0 Overview
1 News
2 Accountinfo
3 Personalinformation

关于python - 如何在 Python 中仅提取 url 的特定部分并将其值添加为 df 中每一行的另一列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52077814/

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