【问题标题】:How to pass an entire column as a parameter to tldextract function?如何将整列作为参数传递给 tldextract 函数?
【发布时间】:2022-03-02 07:31:24
【问题描述】:

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 我无法将数据直接放在这里。所以,我要发布一个快照。

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    使用 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
    

    【讨论】:

    • 显示同样的错误:TypeError: expected string or bytes-like object
    • @Vaidehi 我对代码进行了测试,它似乎工作正常。我可以查看您的完整代码和输入数据吗?
    猜你喜欢
    • 2019-08-21
    • 2013-01-27
    • 1970-01-01
    • 2022-12-03
    • 2020-12-18
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多