【问题标题】:looping to pull the first 2 substrings of a column in python循环拉取python中列的前2个子字符串
【发布时间】:2019-03-15 03:18:15
【问题描述】:

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

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?

【问题讨论】:

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

标签: python pandas loops for-loop substring


【解决方案1】:

我相信你可以使用extract 来返回第一个匹配的模式:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 2014-08-05
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 2018-04-01
    相关资源
    最近更新 更多