gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:36:00 24 4
gpt4 key购买 nike

我有一个 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/

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