将数据从宽表转为长表(Unpivot)
您已经对 Spotify 数据做了分组聚合(groupby-aggregation),在 DataFrame wide_df 中得到了每位艺人每年的播放量统计。现在,您希望把 wide_df 中的数据转换为长表格式,以便用于数据可视化。
本练习是课程的一部分
Polars 入门
练习说明
- 使用
"artist"和"year"作为索引列来标识每一行的数据。 - 对
wide_df中的统计列进行反透视(unpivot):"avg_streams"、"max_streams"、"min_streams"。 - 将变量列命名为
"metric",将数值列命名为"stream_count"。
交互式实操练习
通过完成这段示例代码来试试这个练习。
long_df = (
wide_df
.unpivot(
# Set the index columns
index=____,
# Unpivot on the stats columns
on=____,
# Name the variable and value columns
variable_name=____,
value_name=____
)
)
print("\nLong format DataFrame:")
print(long_df)