我有一个数据框,其列名如下所示,其中一些列名在 [] 中包含子字符串
'date', 'customer','region[level1]','priority[s2]','planning[WIP]' ...
Jan.10, ABC , East[3] , Normal[1] , TBD[WIP] ...
我想重命名所有列,以便只保留 [] 中的值。
'date','customer','level1','s2','WIP' ...
我试过下面的代码,但一直收到错误代码“NoneType”对象没有属性“组”。哪一部分出了问题?
import re
for i in range(len(df.columns)):
df.columns.value[i] = [re.match(r"[^[]*\[([^]]*)\]", col_name).groups()[0] for col_name in df.columns]
一些注意事项:
re.match
仅在字符串开头搜索匹配项,re.search
用于在字符串内的任何位置查找匹配项[^[]*\[([^]]*)\]
匹配零或比其他更多的字符[
,然后[
,零个或多个比其他字符]
,然后]
和它看起来不错,但它是一个模式,你应该使用.str.replace
(见下文)。'NoneType' object has no attribute 'groups'
问题,因为某些标头与您的模式不匹配(请参阅上面的正则表达式演示。)您可以使用
import pandas as pd
df = pd.DataFrame([['Jan.10','ABC','East[3]','Normal[1]','TBD[WIP]']], columns=['date','customer','region[level1]','priority[s2]','planning[WIP]'])
df.columns = df.columns.str.replace(r'.*\[([^][]*)].*', r'\1', regex=True)
>>> df
date customer level1 s2 WIP
0 Jan.10 ABC East[3] Normal[1] TBD[WIP]
在.*\[([^][]*)].*
正则表达式匹配
.*
- 尽可能多的除换行符以外的零个或多个字符\[
- 一个[
字符([^][]*)
- 第 1 组:除[
和之外的任何零个或多个字符]
].*
-]
字符和行的其余部分。请参阅正则表达式演示。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句