我有以下格式的数据框。
想要修改列名称并将数据框重新排列为以下格式:-
我尝试使用下面的代码将列名称从对象转换为列表,然后剥离和拆分字符串。但这样做后仍然有空格。不知道为什么。
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'([A-Z]{4})(\d{4})(.+)' 更改匹配组的模式
并使用 Series.str.extract
对于新助手 DataFrame
- 将第二列转换为整数,连接在一起并分配回来。
然后使用 Series.str.split
对于MultiIndex
,通过 DataFrame.stack
reshape 和数据清理-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
列,只需将列
替换为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
关于python - pandas 数据帧上的正则表达式更改列名称,然后重新排列数据帧的格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55549863/