首页 > 解决方案 > 根据在另外两列中定义的开始和停止索引位置提取数据框中的子字符串

问题描述

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')

标签: pythonpandasdataframesubstringapply

解决方案


用于.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

推荐阅读