首页 > 解决方案 > 使用另一列作为索引的 Pandas 子字符串

问题描述

我正在尝试使用包含起始索引的一列来子选择一个字符串列。

df = pd.DataFrame({'string': ['abcdef', 'bcdefg'], 'start_index': [3, 5]})
expected = pd.Series(['def', 'g'])

我知道您可以使用以下内容进行子字符串

df['string'].str[3:]

但是,就我而言,开始索引可能会有所不同,所以我尝试了:

df['string'].str[df['start_index']:]

但它返回 NaN。

编辑:如果我不想使用循环/列表理解怎么办?即首选矢量化方法。

EDIT2:在这个小测试用例中,列表理解似乎更快。

from itertools import islice
%timeit df.apply(lambda x: ''.join(islice(x.string, x.start_index, None)), 1)
%timeit pd.Series([x[y:] for x , y in zip(df.string,df.start_index) ])

631 µs ± 1.96 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
101 µs ± 233 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

标签: pythonstringpandassubstring

解决方案


使用 for loop with zipof two columns ,为什么我们在这里使用 for 循环,您可以查看链接

[x[y:] for x , y in zip(df.string,df.start_index) ]
Out[328]: ['def', 'g']

推荐阅读