【发布时间】:2019-10-29 12:35:04
【问题描述】:
我正在尝试使用包含起始索引的一列来子选择一个字符串列。
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。
编辑: 如果我不想使用循环/列表理解怎么办?即首选矢量化方法。
编辑2: 在这个小测试用例中,列表理解似乎更快。
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)
【问题讨论】:
-
所有字符串的长度都一样吗?
-
不,他们没有。
标签: python string pandas substring