Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 根据在其他两列中定义的开始和停止索引位置提取dataframe中的子字符串_Python_Pandas_Dataframe_Substring_Apply - Fatal编程技术网

Python 根据在其他两列中定义的开始和停止索引位置提取dataframe中的子字符串

Python 根据在其他两列中定义的开始和停止索引位置提取dataframe中的子字符串,python,pandas,dataframe,substring,apply,Python,Pandas,Dataframe,Substring,Apply,我需要使用str.slicestart=start,stop=stop来提取dataframedf的Seq列中的子字符串,并将名为start和stop的列中的值用作dataframe的每一行的开始和停止值 我想使用def函数或lambda,但出现错误 df= "start", "stop", "Seq" 50 121 aaaaaaaaaaaaabbbbbbbbbbbbcccccccccc...dddddd 25 150 aaaaahhhhhhhsss

我需要使用str.slicestart=start,stop=stop来提取dataframedf的Seq列中的子字符串,并将名为start和stop的列中的值用作dataframe的每一行的开始和停止值

我想使用def函数或lambda,但出现错误

df=  "start", "stop", "Seq"
   50       121   aaaaaaaaaaaaabbbbbbbbbbbbcccccccccc...dddddd
   25       150   aaaaahhhhhhhssssssssssssssccccccccc...dddddd
输出: KeyError:“开始”,“在索引id处发生”

使用。应用以:字符串[start:stop]的形式在每一行上应用切片

如果要定义函数,请执行以下操作:

df.apply(lambda x: x['Seq'][x['start']:x['stop']], axis=1)

0      aaabbbbbbbb
1    sssssssssssss
dtype: object
或者使用具有列表理解功能的zip:

使用的输入数据帧:

可能重复的
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)
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