将列中的值转换为列标题,将列标题转换为单列中的值

  • 本文关键字:标题 转换 单列中 python pandas
  • 更新时间 :
  • 英文 :


我有这个数据帧:

>优先年份当前年份<1><2>元素#2元素#3
大学id# 年份fin_element
1 2022 元素#1
1 20223美元5美元
1 20222美元0美元

试试这个:

out = (df
.set_index(['University_id', 'Year', 'fin_element'])
.stack()
.unstack(level=2)
.rename(columns={'level_2' : 'financial_period'})
.reset_index()
)
print(out)
fin_element  University_id  Year financial_period element #1 element #2 element #3
0                        1  2022       prior_year         $1         $3         $2
1                        1  2022     current_year         $2         $5         $0

最新更新