python - 在熊猫列中第二次出现后获取前 4 个字符之前的所有子字符串
问题描述
我有以下数据框:
import pandas as pd
data = {'URL': ['https://weibo.com/6402575118/Iy0zjtMNZ', 'https://weibo.com/6402575118/Hellothere', 'https://weibo.com/6402575118/hithere']}
df = pd.DataFrame(data, columns=['URL'])
我想在第二次出现“/”之后将所有子字符串直到第四个字符,这样:
data = {'URL': ['https://weibo.com/6402575118/Iy0z', 'https://weibo.com/6402575118/Hell', 'https://weibo.com/6402575118/hith']}
df = pd.DataFrame(data, columns=['URL'])
我该如何实现?
我知道如何拆分并获取字符串的第一部分,即
df['URL'] = df['URL'].str.split("/").str[0]
但我不确定如何施加发生条件?
解决方案
如果在第 4 次/
使用Series.str.split
with后需要替换n=4
,则加入并添加为第一个值5th
过滤的字符串:4
str.cat
s = df['URL'].str.split("/", n=4)
df['URL'] = s.str[:4].str.join('/').str.cat(s.str[4].str[:4], '/')
print (df)
URL
0 https://weibo.com/6402575118/Iy0z
1 https://weibo.com/6402575118/Hell
2 https://weibo.com/6402575118/hith
另一个想法是rsplit
从右侧拆分:
s = df['URL'].str.rsplit("/", n=1)
df['URL'] = s.str[0].str.cat(s.str[-1].str[:4], '/')
print (df)
URL
0 https://weibo.com/6402575118/Iy0z
1 https://weibo.com/6402575118/Hell
2 https://weibo.com/6402575118/hith
推荐阅读
- bash - 表达式的日期增量
- django - “文件上传”按钮在 django 中不可见(虽然在 django 管理面板中可见)
- node.js - 在 fastify 中使用通配符路由
- python - 如何在 Python 包中包含 tar.gz 文件?
- google-cloud-platform - 使用谷歌云功能记录文件下载并将文件下载到客户端
- graphql - 无法为graphql中的不可空字段返回null
- laravel - 是否可以在用户使用一次后不允许用户访问 Create CRUD?
- rust - Why is there is no dedicated method for creating a String from a UTF8-encoded array?
- c# - What is the proper way of handling object reference when applying projections in EF Core?
- linux - HAProxy reqrep 请求操作