python - 使用另一列作为索引的 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)
解决方案
使用 for loop with zip
of two columns ,为什么我们在这里使用 for 循环,您可以查看链接
[x[y:] for x , y in zip(df.string,df.start_index) ]
Out[328]: ['def', 'g']
推荐阅读
- drools - drools-7.23.0.Final KieContainerImpl KieBaseException
- c - 为什么 UDP 套接字不接收来自 nc -u 主机端口的 udp 流量?
- hadoop - Kerberos HBase Zookeeper 失败
- powershell - 为什么对象在多次使用后会被破坏?
- sql-server - 下面的 SQLServer 视图适合哪个 select 语句?
- node.js - Graphql 获取动态数据的聚合
- javascript - 如何在多个按钮中使用相同的功能以获得相同的结果?
- swift - 如何使视图集合并立即更改它们的圆角?
- java - Mojo Codehaus 属性插件替代品
- python - 如何读取配置文件?