我有一个数据集,我希望其中的一些值成为列标题,以及交叉表格式.
数据
year qtr ID type growth re nondd_re se_re or
2024 2024Q1 NY aa 3.18 1.14 0 0 0
2024 2024Q2 NY aa 2.1 1.14 0 0 0
2024 2024Q1 NY dd 6.26 3.07 3.07 0 0
2024 2024Q2 NY dd 4.13 3.07 3.07 0 0
2024 2024Q1 CA aa 0 0 0 0 0
2024 2024Q2 CA aa 0.03 0 0 0 0
2024 2024Q1 CA dd 0 0 0 0 0
2024 2024Q2 CA dd 0.06 0 0 0 0
所需
ID type type 2024Q1 2024Q2
NY growth dd 6.26 4.13
NY nond_ re dd 3.07 3.07
NY se_re dd 0 0
NY or dd 0 0
NY re dd 3.07 3.07
NY growth aa 3.18 2.1
NY nond_ re aa 0 0
NY se_re aa 0 0
NY or aa 0 0
NY re aa 1.14 1.14
CA growth dd 0 0.6
CA nond_ re dd 0 0
CA se_re dd 0 0
CA or dd 0 0
CA re dd 0 0
CA growth aa 0 0.3
CA nond_ re aa 0 0
CA se_re aa 0 0
CA or aa 0 0
CA re aa 0 0
做
# Melt the 数据frame to transform metrics columns into rows
melted_df = df.melt(id_vars=["year", "qtr", "ID", "type"], var_name="type", value_name="value")
# Pivot the melted 数据frame
pivot_df = melted_df.pivot_table(index=["ID","type"], columns="qtr", values="value", fill_value=0)
# Reset index to turn multi-index into columns
pivot_df = pivot_df.reset_index()
问题是,所有的价值观都没有得到.上面的代码生成了带有缺失值的输出 任何建议都很感激