重新排列标题数据框中的单词

问题描述 投票:0回答:1

我有一个数据框:

df = pd.DataFrame({ 
'FY18Q1': [ 1500, 1200, 950, 2200], 
'FY18Q2': [ 2340, 1234, 2000, 1230],
'FY18Q3': [2130, 2200, 2190, 2210],   
'FY18YearTotal': [1000, 1900, 1500, 1800]})

我想重新排列标题的顺序。我希望标题读取“1Q18”,其中“FY181Q”,“FY18”,其中读取“FY18YearTotal”

我可以通过以下方式删除“FY”和“YearTotal”:

df.columns = df.columns.str.replace(r"(|FY|\.)", "")
df.columns = df.columns.str.replace(r"(|YearTotal|\.)", "")

但这并不能让我:

df = pd.DataFrame({ 
'1Q18': [ 1500, 1200, 950, 2200], 
'2Q18': [ 2340, 1234, 2000, 1230],
'3Q18': [2130, 2200, 2190, 2210],   
'FY18': [1000, 1900, 1500, 1800]})
pandas header
1个回答
0
投票

您可以简单地将两个调用链接到

str.replace

df.columns = df.columns.str.replace(r'^FY(\d+)Q(\d+)', r'\2Q\1')
                       .str.replace(r'YearTotal$', r'')
© www.soinside.com 2019 - 2024. All rights reserved.