Python 如何使用正则表达式匹配按列对数据帧进行分组

Python 如何使用正则表达式匹配按列对数据帧进行分组,python,regex,pandas,Python,Regex,Pandas,我有以下数据框: import pandas as pd df = pd.DataFrame({'id':['a','b','c','d','e'], 'XX_111_S5_R12_001_Mobile_05':[-14,-90,-90,-96,-91], 'YY_222_S00_R12_001_1-999_13':[-103,0,-110,-114,-114], 'ZZ_111_S

我有以下数据框:

import pandas as pd
df = pd.DataFrame({'id':['a','b','c','d','e'],
                   'XX_111_S5_R12_001_Mobile_05':[-14,-90,-90,-96,-91],
                   'YY_222_S00_R12_001_1-999_13':[-103,0,-110,-114,-114],
                   'ZZ_111_S00_R12_001_1-999_13':[1,2.3,3,5,6],
})

df.set_index('id',inplace=True)
df
看起来是这样的:

Out[6]:
    XX_111_S5_R12_001_Mobile_05  YY_222_S00_R12_001_1-999_13  ZZ_111_S00_R12_001_1-999_13
id
a                           -14                         -103                          1.0
b                           -90                            0                          2.3
c                           -90                         -110                          3.0
d                           -96                         -114                          5.0
e                           -91                         -114                          6.0
我要做的是根据以下正则表达式对列进行分组:

\w+_\w+_\w+_\d+_([\w\d-]+)_\d+
因此,最终它是按
Mobile
1-999
进行分组的

怎么做。我尝试了这一点,但未能将其分组:

import re
grouped = df.groupby(lambda x: re.search("\w+_\w+_\w+_\d+_([\w\d-]+)_\d+", x).group(), axis=1)
for name, group in grouped:
    print name
    print group
其中打印:

XX_111_S5_R12_001_Mobile_05
YY_222_S00_R12_001_1-999_13
ZZ_111_S00_R12_001_1-999_13
我们需要的是
name
打印到:

Mobile
1-999
1-999

group
打印相应的数据帧。

分组后,将新数据帧的索引设置为
[re.findall(r'\w+\uw+\uw+\w+\ud+\u([\w\d-]+)\ud+',col)[0]用于df.columns中的col
(即
['Mobile',1-999',1-999']
)。

您可以在列上使用
<

# Performing the groupby.
pat = '\w+_\w+_\w+_\d+_([\w\d-]+)_\d+'
grouped = df.groupby(df.columns.str.extract(pat, expand=False), axis=1)

# Showing group information.
for name, group in grouped:
    print name
    print group, '\n'
返回所需的组:

1-999
    YY_222_S00_R12_001_1-999_13  ZZ_111_S00_R12_001_1-999_13
id                                                          
a                          -103                          1.0
b                             0                          2.3
c                          -110                          3.0
d                          -114                          5.0
e                          -114                          6.0 

Mobile
    XX_111_S5_R12_001_Mobile_05
id                             
a                           -14
b                           -90
c                           -90
d                           -96
e                           -91 

您的正则表达式有一些问题,
\w
匹配包含下划线的单词字符,这似乎不是您想要的,如果您只想匹配字母和数字,使用
A-Za-z0-9-
会更好:

df.groupby(df.columns.str.extract("([A-Za-z0-9-]+)_\d+$"), axis=1).sum()

基于错误的描述,我似乎忽略了你的问题。您遇到的问题与分组无关。它与索引有关。你能提供一些关于你想要达到的目标的额外细节吗?看起来您正试图在groupby中输出3个组,而原始数据框中仍然只有3列。此外,根据groupby的定义,组名称/标签(您称之为
名称
)是唯一的,因此您描述的所需输出是不可能的;最接近的方法是创建一行标签(即Mobile和1-999),并在您的组中使用这些标签,但我不确定这是否与您的尝试相关。