在一列上进行复杂转换,同时在Python/Pandas中保留原始列

2024-10-08 18:28:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框df,我希望在我的列中用特定的值分隔来显示第一个单词和数字以及它的“T”值。我想要第一个用“-”分隔的“单词”及其#T值

数据

type                                        total   free   use

AY12-AYY-AY-R800-900G-12T_18T-R6-v.A        10      5      5
AY12-AYY-AY-R800-900G-12T_18T-R6-v.A        10      4      6
AY12-AYY-AY-R800-900G-12T_18T-R6-v.A        10      1      9
AY12-AYY-AY-R800XD-900G-6.4T-R11-WOW-v.A    10      8      2
AY12-AYY-AY-R800XD-900G-6.4T-R11-WOW-v.A    10      3      7

所需的

type            total   free   use

AY12 12T        10      5      5
AY12 12T        10      4      6
AY12 12T        10      1      9
AY12 6.4T       10      8      2
AY12 6.4T       10      3      7

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', 'total', 'free', 'use']

但是,转换没有发生,这是结果:

type                                        total   free   use

AY12-AYY-AY-R800-900G-12T_18T-R6-v.A        10      5      5
AY12-AYY-AY-R800-900G-12T_18T-R6-v.A        10      4      6
AY12-AYY-AY-R800-900G-12T_18T-R6-v.A        10      1      9
AY12-AYY-AY-R800XD-900G-6.4T-R11-WOW-v.A    10      8      2
AY12-AYY-AY-R800XD-900G-6.4T-R11-WOW-v.A    10      3      7

我还在研究。任何帮助或建议都将不胜感激


Tags: 数据freedfusetyperegextotalwow
2条回答

虽然我确信有一个更优雅的解决方案,但这应该是可行的

df['type'] = df['type'].apply(lambda x: ' '.join(re.findall(r'(^.+?)-.+?(\d+(?:\.\d+)?T)', x)[0]))

您是否尝试过:

df['type']=df['type'].str.extract('(\w+(?=[-AYY]))')+ " "+ df['type'].str.extract('(?<=0G-)(.*?)(?=\-|_)')



     type  total  free  use
0   AY12 12T     10     5    5
1   AY12 12T     10     4    6
2   AY12 12T     10     1    9
3  AY12 6.4T     10     8    2
4  AY12 6.4T     10     3    7

相关问题 更多 >

    热门问题