python中的循环和字符串数组 [英] Loop and arrays of strings in python

查看:351
本文介绍了python中的循环和字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据集:

column1

HL111
PG3939HL11
HL339PG
RC--HL--PG

我正在尝试编写一个执行以下操作的函数:

I am attempting to write a function that does the following:

  1. 遍历column1的每一行
  2. 仅拉字母并放入数组
  3. 如果数组中包含"HL",则将其从数组中删除,除非HL是数组中的唯一单词.
  4. 取数组中的第一个单词并输出结果.

因此对于上面的示例,我的数组(第2步)将如下所示:

So for the above example, my array (step2) would look like this:

[HL]
[PG,HL]
[HL,PG]
[RC,HL,PG]

和我想要的最终输出(第4步)如下所示:

and my desired final output (step4) would look like this:

desired_column

HL
PG
PG
RC

我有第2步的代码,看来工作正常

I have the code for step 2, and it seems to work fine

df['array_column'] = (df.column1.str.extractall('([A-Z]+)')
                    .unstack()
                    .values.tolist())

但是我不知道如何从这里到我的最终输出(步骤4).

But I don't know how to get from here to my final output (step4).

推荐答案

通过替换所有非字母,然后提取字母对,然后应用一些自定义逻辑从数组中提取必要的值,可以实现所需的功能:

You may achieve what you need by replacing all non-letters first, then extracting pairs of letters and then applying some custom logic to extract the necessary value from the array:

>>> df['array_column'].str.replace('[^A-Z]+', '').str.findall('([A-Z]{2})').apply(lambda d: [''] if len(d) == 0 else d).apply(lambda x: 'HL' if len(x) == 1 and x[0] == 'HL' else [m for m in x if m != 'HL'][0])
0    HL
1    PG
2    PG
3    RC
Name: array_column, dtype: object
>>> 

详细信息

  • .replace('[^A-Z]+', '')-删除所有大写字母以外的字符
  • .str.findall('([A-Z]{2})')-提取字母对
  • 如果上一步中没有正则表达式匹配,
  • .apply(lambda d: [''] if len(d) == 0 else d)将添加一个空项目
  • .apply(lambda x: 'HL' if len(x) == 1 and x[0] == 'HL' else [m for m in x if m != 'HL'][0])-自定义逻辑:如果列表长度为1并且等于HL,则保留它,否则删除所有HL并获取第一个元素
  • .replace('[^A-Z]+', '') - remove all chars other the uppercase letters
  • .str.findall('([A-Z]{2})') - extract pairs of letters
  • .apply(lambda d: [''] if len(d) == 0 else d) will add an empty item if there is no regex match in the previous step
  • .apply(lambda x: 'HL' if len(x) == 1 and x[0] == 'HL' else [m for m in x if m != 'HL'][0]) - custom logic: if the list length is 1 and it is equal to HL, keep it, else remove all HL and get the first element

这篇关于python中的循环和字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆