python - Pandas 使用 tldextract 加入单元格中的最后 2 个逗号分隔项

标签 python pandas

我有一个 pandas 数据框,并且正在使用 tldextract 库。我在创建新列和连接第二个和第三个分隔字符串时遇到问题。

#First 5 rows for testing purposes
df = pd.DataFrame(request['destinationhostname'].iloc[0:5])

    destinationhostname
0   pod51042psh.outlook.com
1   s.mrmserve.com
2   client-office365-tas.msedge.net
3   otf.msn.com
4   log.pinterest.com

#Applying tld extract on destinationhostname column
df['req'] = request.destinationhostname.apply(tldextract.extract)

    destinationhostname              req
0   pod51042psh.outlook.com         (pod51042psh, outlook, com)
1   s.mrmserve.com                  (s, mrmserve, com)
2   client-office365-tas.msedge.net (client-office365-tas, msedge, net)
3   otf.msn.com                     (otf, msn, com)
4   log.pinterest.com               (log, pinterest, com)

我已尝试通过以下多种方式来完成下一部分,但不断出现错误。

df['fld'] = df['req'].apply('.'.join[1:3])

TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'

或者

TypeError: sequence item 0: expected string, ExtractResult found

我想要的输出是:

    destinationhostname             req                                  fld
0   pod51042psh.outlook.com         (pod51042psh, outlook, com)          outlook.com
1   s.mrmserve.com                  (s, mrmserve, com)                   mrmserve.com
2   client-office365-tas.msedge.net (client-office365-tas, msedge, net)  msedge.net
3   otf.msn.com                     (otf, msn, com)                      msn.com
4   log.pinterest.com               (log, pinterest, com)                pinterest.com

最佳答案

切片 str 对象然后 join

df['fld'] = df.req.str[1:].str.join('.')

df

               destinationhostname                                  req            fld
0          pod51042psh.outlook.com          (pod51042psh, outlook, com)    outlook.com
1                   s.mrmserve.com                   (s, mrmserve, com)   mrmserve.com
2  client-office365-tas.msedge.net  (client-office365-tas, msedge, net)     msedge.net
3                      otf.msn.com                      (otf, msn, com)        msn.com
4                log.pinterest.com                (log, pinterest, com)  pinterest.com

或作为 @coldspeed has shown ,您可以使用数组引用的结尾进行切片。

df['fld'] = df.req.str[-2:].str.join('.')

关于python - Pandas 使用 tldextract 加入单元格中的最后 2 个逗号分隔项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53725828/

相关文章:

python - 如果列表,Pandas 将列值拆分为新列

Python Pandas/tqdm 显示提取进度

python - 无法关闭 KeyboardInterrupt 上的套接字

python - 在 Python 中使用字典翻译短语

java - 在开发中的 docker 容器中创建新镜像或共享卷中的源代码?

python - Pandas 数据框 - 使用通配符选择行

python pandas pivot_table 在一列中计算频率

pandas - 计算数据框中特定列中的 NaN

python - Qt python 如何知道QPushButton发送了哪些信号?

python - 关于python中numpy矩阵的问题