python-3.x - 如何将整列作为参数传递给 tldextract 函数?

标签 python-3.x

tldextract 用于从 URL 中提取域名。这里,'url' 是数据框 'df' 中的列名之一。可以将 'url' 的一个值作为参数传递。但是,我无法将整个列作为参数传递。
这里传递的 url 是 ' https://www.google.com/search?source=hp&ei=7iE '

listed = tldextract.extract(df['url'][0])
dom_name = listed.domain
print(dom_name)

输出:
谷歌

我想要的是在名为“域”的数据框中创建一个新列,其中包含从 URL 中提取的域名。

就像是:
df['Domain'] = tldextract.extract(df['url'])

但这不起作用

这是代码:
# IMPORTING PANDAS
import pandas as pd
from IPython.display import display

import tldextract

# Read data sample
df = pd.read_csv("bookcsv.csv")

df['Domain'] = df['url'].apply(lambda url: tldextract.extract(url).domain)

这是输入数据:

The dataframe looks like this
我不能直接把数据放在这里。所以,我发布了一个快照。

最佳答案

使用 apply 和 apply 函数应用于列中的每个元素,并将使所有内容整齐排列。

df['Domain'] = df['url'].apply(lambda url: tldextract.extract(url).domain)

这是我用于测试的完整代码:
import pandas as pd, tldextract

df = pd.DataFrame([{'url':'https://google.com'}]*12)
df['Domain'] = df['url'].apply(lambda url: tldextract.extract(url).domain)
print(df)

输出:
                   url  Domain
0   https://google.com  google
1   https://google.com  google
2   https://google.com  google
3   https://google.com  google
4   https://google.com  google
5   https://google.com  google
6   https://google.com  google
7   https://google.com  google
8   https://google.com  google
9   https://google.com  google
10  https://google.com  google
11  https://google.com  google

关于python-3.x - 如何将整列作为参数传递给 tldextract 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51347800/

相关文章:

python - 合并数据框列表以创建一个数据框

Python - 使用 RegEx 操作字符串

python - 在 Pandas 中处理多个数据帧的优雅方式

python - 如何在 Python 3 中将字典列表保存到 .mat 文件中?

python - 如何在 Python 中打开名称中包含或以 # 开头的模块?

python-3.x - 如果小数为 0,Pandas 将 float 转换为 int

python - 让 Tkinter 等到按下按钮

python-3.x - 如何使用 Pandas 按降序和时间按升序对日期进行排序

python-3.x - 使用正则表达式确定字符串的字符顺序是否正确

python - 如何找到字符串的可能组合总数?