【问题标题】:Pandas substring using another column as the index使用另一列作为索引的 Pandas 子字符串
【发布时间】: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


【解决方案1】:

使用for循环和两列的zip,为什么我们在这里使用for循环,你可以查看link

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

【讨论】:

猜你喜欢
  • 2016-04-18
  • 2022-11-26
  • 2014-05-09
  • 2020-07-07
  • 1970-01-01
  • 1970-01-01
  • 2016-09-04
  • 2020-12-05
  • 2022-07-06
相关资源
最近更新 更多