python - 基于其他列的python pandas切片字符串
问题描述
我正在尝试根据其他两列中的值(理想情况下是方法链接的)对列中的字符串进行切片:
df = pd.DataFrame({'a':["abcde", "abcdefg"], 'start':[0,3], 'end':[3,5]})
df.assign(c = lambda x: x.a.str.slice(x.start,x.end))
返回:
a start end c
0 abcde 0 3 NaN
1 abcdefg 3 5 NaN
预期的:
a start end c
0 abcde 0 3 abc
1 abcdefg 3 5 def
解决方案
使用适用:
df.assign(c = lambda x: x.apply( lambda s: s['a'][s.start:s.end],axis=1))
推荐阅读
- c# - 如何模拟方法调用内部另一个方法的返回
- python-3.x - 用户定义的函数存储在哪里?
- java - 自定义视图的适配器中的 NullPointerException
- java - 使用泛型从三个相似的方法中创建一个简洁的方法
- python - Google Drive API Python客户端:批量创建时如何检索创建的文件夹ID列表?
- python - Keras 形状'ValueError'
- c++ - Windows10 + Ubuntu 20.04 上的 CUDA 问题
- xml - Perl 探查器中断对 XML 解析器的调用
- android - 将 Room LiveData 的结果设置为文本视图
- javascript - 使用 Bazel 构建多语言项目