Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.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中列的前2个子字符串_Python_Pandas_Loops_For Loop_Substring - Fatal编程技术网

循环以提取python中列的前2个子字符串

循环以提取python中列的前2个子字符串,python,pandas,loops,for-loop,substring,Python,Pandas,Loops,For Loop,Substring,我试图通过以下方式从列中提取子字符串: target_column: PE123 DD123-HP123 HP123 373627HP23 我想提取每个记录的前两个字符串/字母表,除非前两个字符串中没有字母表。在这种情况下,拉动字符串其余部分中找到的任何字母表。因此,在373627HP23的情况下,它将拉动HP 但问题在于DD123-HP123之类的东西。我的循环是拉HP而不是DD for index,row in df.iterrows(): target_value = row

我试图通过以下方式从列中提取子字符串:

target_column: 

PE123
DD123-HP123
HP123
373627HP23
我想提取每个记录的前两个字符串/字母表,除非前两个字符串中没有字母表。在这种情况下,拉动字符串其余部分中找到的任何字母表。因此,在373627HP23的情况下,它将拉动HP

但问题在于DD123-HP123之类的东西。我的循环是拉HP而不是DD

for index,row in df.iterrows():
    target_value = row['target_column']
    predefined_code = [HP]           
     for code in re.findall("[a-zA-Z]+", target_value):
         if (len(code)!=1) and not (code in predefined_code):
             possible_code = code
我的代码有什么问题

编写循环的最佳代码是什么,以便在DD123-HP123这样的情况下,它将拉动DD而不是HP

我相信您可以使用返回优先匹配模式:

df['new'] = df['target_column'].str.extract("([a-zA-Z]+)")
print (df)
  target_column new
0         PE123  PE
1   DD123-HP123  DD
2         HP123  HP
3    373627HP23  HP

预期输出是什么?以下是预期输出SPE DD HP HPOK,添加的解决方案,请检查是否使用真实数据。