我有一个数据框df,我希望在我的列中用特定的值分隔来显示第一个单词和数字以及它的'T'值。我想要第一个用“-”分隔的单词及其T值。这是棘手的,因为有些T值用“-”分隔,而其他值则用“#”分隔。 例如,其中一个值中的-12T,以及另一个值中的\u 14T
数据:
type free use total
Hello-HEL-HE-A6123-123A-12T_TYPE-v.A 10 10 20
Hello-HEL-HE-A6123-123A-12T_TYPE-v.E 5 1 6
Hello-HEL-HE-A6123-123A-50T_TYPE-v.C 1 4 5
Hello-HEL-HE-A6123-123A-50T_TYPE-v.A 2 1 1
Happy-HAP-HA-R650-570A-90T_version-v.A 10 0 10
Kind-KIN-KI-T490-NET_14T-A.0 7 4 3
Kind-KIN-KI-T490-NET_14T-A.0 6 3 2
AY14.5-fyy-FY-R770-256G-6.4T-R1-v.A 3 0 3
AY14.5-fyy-FY-R770-256G-6.4T-R1-v.A 0 20 20
所需:
type free use total
Hello 12T 10 10 20
Hello 12T 5 1 6
Hello 50T 1 4 5
Hello 50T 2 1 1
Happy 90T 10 0 10
Kind 14T 7 4 3
Kind 14T 6 3 2
AY14.5 6.4T 3 0 3
AY14.5 6.4T 0 20 20
正在做:
df['type']=df['type'].str.extract('(\w+(?=[-AYY]))')+ " "+ df['type'].str.extract('(?<=0G-)(.*?)(?=\-|_)')
这在下面起作用,但是,只有被转换的列仍然存在。其他列不存在:
import pandas as pd
def extract_value(s):
regex = re.search(r'(^.+?)-.+?(\d+(?:\.\d+)?T)', s)
if regex:
first_word = regex.group(1)
code = regex.group(2)
return f'{first_word} {code}'
return s
df.columns = ['type']
df['type'] = df[type'].apply(lambda x: extract_value(x))
但是,这仅提取具有特定模式的值。我如何将此应用于完整的样本集
感谢您的建议,我仍在排除故障
当然!可以使用此正则表达式一次性捕获所需的所有内容。我在正则表达式中包含了注释。为了通知
re
,我传递了标志re.X
,这意味着此模式是一个“详细”模式,其中包含在执行实际匹配时应忽略的注释现在我们已经提取了相关的信息位,我们可以继续将它们粘在一起以覆盖旧的
"type"
列:与常规正则表达式一样,这可能无法捕获所有角落的情况,但我希望它阐明了如何使用正则表达式和捕获组从列中收集相关信息的方法
相关问题 更多 >
编程相关推荐