首页 > 解决方案 > 在熊猫列中第二次出现后获取前 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]

但我不确定如何施加发生条件?

标签: pythonpandasstring

解决方案


如果在第 4 次/使用Series.str.splitwith后需要替换n=4,则加入并添加为第一个值5th过滤的字符串:4str.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

推荐阅读