python - 根据在另外两列中定义的开始和停止索引位置提取数据框中的子字符串
问题描述
df= "start", "stop", "Seq"
50 121 aaaaaaaaaaaaabbbbbbbbbbbbcccccccccc...dddddd
25 150 aaaaahhhhhhhssssssssssssssccccccccc...dddddd
我需要使用 str.slice(start=start, stop=stop) 提取数据帧(df)的列“Seq”中的子字符串,使用名为“start”和“stop”的列中的值作为开始和停止值(对于数据帧的每一行)。
我想使用 def 函数或 lambda,但出现错误
def f(x,y,z):
return z.str.slice(start=x, stop=y)
df.apply(lambda x: f(x["start"],x["stop"],x["Seq"]))
输出: KeyError: ('start', '发生在索引 id')
解决方案
用于.apply
以以下形式对每一行应用切片:string[start:stop]
df.apply(lambda x: x['Seq'][x['start']:x['stop']], axis=1)
0 aaabbbbbbbb
1 sssssssssssss
dtype: object
如果要定义一个函数:
def slice_str(string, start, stop):
return string[start:stop]
df.apply(lambda x: slice_str(x['Seq'], x['start'], x['stop']), axis=1)
或zip
与 一起使用list comprehension
:
slices = [string[start:stop] for string, start, stop
in zip(df['Seq'], df['start'], df['stop'])]
['aaabbbbbbbb', 'sssssssssssss']
使用的输入数据框:
start stop Seq
0 10 21 aaaaaaaaaaaaabbbbbbbbbbbbccccccccccdddddd
1 12 25 aaaaahhhhhhhsssssssssssssscccccccccdddddd
推荐阅读
- ios - Swift:在没有文本时以编程方式使用 numberOfLines 展开 UILabel
- vim - 如何在不提示“将更改保存到无标题?”的情况下关闭 gvim?
- windows - 具有本机反应的 Windows 应用程序
- python-3.x - 尝试使用 Python 和 psycopg2 创建 Redshift 表,但未创建表且未报告错误
- php - 我正在尝试跳过结帐页面中的付款地址
- julia - 使用 map 将 Int32 类型的新列添加到 julia 数据框
- python-3.x - Python Selenium 如何定位和填写这 3 个输入
- python - 带参数的 Python/Flask 嵌套装饰器
- python - TypeError: if 语句中 -: 'str' 和 'int' 的不支持的操作数类型
- python - Jupyter Notebook在markdown中位置嵌入图像