# Save Columns
df = df.set_index('refnum')
# Create a MultiIndex with Numbers at the end and split into multiple levels
df.columns = (
df.columns.str.replace(r'^(.*?)(\d+)(.*)$', r'\1\3/\2', regex=True)
.str.split('/', expand=True)
)
# Wide Format to Long + Rename Columns
df = df.stack().droplevel(-1).reset_index().rename(
columns={'y': 'Year', 'ygp': 'GP', 'yrev': 'REV'}
)
# Add Base Year Column
df['BaseYear'] = "BaseYear+" + df.groupby('refnum').cumcount().astype(str)
# df['BaseYear'] = df.groupby('refnum').cumcount() # (int version)
尝试:
印刷品:
您可以使用来自
pyjanitor
的pivot_longer
;对于这种情况,将正则表达式传递给names_pattern
,并在names_to
中传递新列名:如果希望包含基准年,可以在使用
pivot_longer
之前修改以数字结尾的列标签:与
.value
相关联的标签保留为列标题,而其余标签则集中到一个新列(base year
)让我们使用^{} 和^{} 然后^{} 将标题转换为可用的多索引,以从宽格式转换为长格式。然后^{} 创建BaseYear列
df
:相关问题 更多 >
编程相关推荐