[英]Regex on pandas dataframe to change column names, then re-arrrage format of dataframe
我有以下格式的数据帧。
想要修改列名并将数据帧重新排列为以下格式: -
我已经尝试了下面的代码将列名从对象转换为列表,然后剥离并拆分字符串。 但这样做之后仍然有空格。 不知道为什么。
df_col_list=df.columns.tolist()
list =[]
for elem in df_col_list:
list.extend(elem.strip().split(':'))
list
移动到正则表达式以替换列名称以填充具有我想要的最终数据帧格式的ID列的那些。
well_pattern=re.compile(r'[A-Z]{4}\d{4}')
for item_list in list:
wellname=re.findall(well_pattern,item_list)
for n in wellname:
fld, well_no= n[:4], int(n[4:8])
item_list = item_list.replace(n, '%s_%d_0' % (fld, well_no))
print(item_list)
它将'MNIF0001'更改为'MNIF_1_0'。 但是,我如何使用此输出来填充最终数据帧格式的新列。
我现在卡住了,不知道该怎么办。 请帮忙
提前致谢
首先通过r'([AZ]{4})(\\d{4})(.+)'
更改匹配组的模式,并将Series.str.extract
用于新的帮助器DataFrame
- 将第二列转换为整数,连接在一起回头。
然后使用Series.str.split
for MultiIndex
,通过DataFrame.stack
重新DataFrame.stack
和数据清理 - DataFrame.rename_axis
, DataFrame.reset_index
和DataFrame.sort_values
:
df = pd.DataFrame({
'MNIF0001:w':[2] * 5,
'MNIF0010:w':[4] * 5,
'MNIF0001:f':[6] * 5,
'MNIF0010:f':[8] * 5,
}, index=['01-Feb-63','01-Mar-63','01-Apr-63','01-May-63','01-Jun-63'])
df.index.name = 'date'
print (df)
MNIF0001:w MNIF0010:w MNIF0001:f MNIF0010:f
date
01-Feb-63 2 4 6 8
01-Mar-63 2 4 6 8
01-Apr-63 2 4 6 8
01-May-63 2 4 6 8
01-Jun-63 2 4 6 8
well_pattern=re.compile(r'([A-Z]{4})(\d{4})(.+)')
df1 = df.columns.to_series().str.extract(well_pattern)
print (df1)
0 1 2
MNIF0001:w MNIF 0001 :w
MNIF0010:w MNIF 0010 :w
MNIF0001:f MNIF 0001 :f
MNIF0010:f MNIF 0010 :f
df.columns = df1[0] + '_' + df1[1].astype(int).astype(str) + '_0' + df1[2]
print (df)
MNIF_1_0:w MNIF_10_0:w MNIF_1_0:f MNIF_10_0:f
date
01-Feb-63 2 4 6 8
01-Mar-63 2 4 6 8
01-Apr-63 2 4 6 8
01-May-63 2 4 6 8
01-Jun-63 2 4 6 8
df.columns = df.columns.str.split(':', expand=True)
df = df.stack(0).rename_axis(('date','ID')).reset_index().sort_values(['ID','date'])
print (df)
date ID f w
4 01-Apr-63 MNIF_10_0 8 4
0 01-Feb-63 MNIF_10_0 8 4
8 01-Jun-63 MNIF_10_0 8 4
2 01-Mar-63 MNIF_10_0 8 4
6 01-May-63 MNIF_10_0 8 4
5 01-Apr-63 MNIF_1_0 6 2
1 01-Feb-63 MNIF_1_0 6 2
9 01-Jun-63 MNIF_1_0 6 2
3 01-Mar-63 MNIF_1_0 6 2
7 01-May-63 MNIF_1_0 6 2
编辑:如果需要使用ID
列只将columns
重新修改为ID
:
df.columns = df.columns.str.split(':', expand=True)
df = df.stack(0).rename_axis(('date','ID')).reset_index().sort_values(['ID','date'])
well_pattern=re.compile(r'([A-Z]{4})(\d{4})')
df1 = df['ID'].str.extract(well_pattern)
df['ID'] = df1[0] + '_' + df1[1].astype(int).astype(str) + '_0'
print (df)
date ID f w
4 01-Apr-63 MNIF_1_0 6 2
0 01-Feb-63 MNIF_1_0 6 2
8 01-Jun-63 MNIF_1_0 6 2
2 01-Mar-63 MNIF_1_0 6 2
6 01-May-63 MNIF_1_0 6 2
5 01-Apr-63 MNIF_10_0 8 4
1 01-Feb-63 MNIF_10_0 8 4
9 01-Jun-63 MNIF_10_0 8 4
3 01-Mar-63 MNIF_10_0 8 4
7 01-May-63 MNIF_10_0 8 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.