详解 Pandas 的 melt 函数

Pandas 的 melt() 函数是用来将 DataFrame 中的很多列重塑转换为两列,一列为原来多列的列名,一列为原来多列对应的列值。

一、数据准备

python 复制代码
import pandas as pd

df = pd.DataFrame({
    "product_id": [0, 1],
    "store1": [95, 70],
    "store2": [100, None],
    "store3": [105, 80]
})
print(df)
复制代码
  product_id  store1  store2  store3
0           0      95   100.0     105
1           1      70     NaN      80

二、方法签名

python 复制代码
def melt(
    frame: DataFrame, # 需重塑转换的 dataframe
    id_vars=None, # 指定不参与转换的列
    value_vars=None,  # 指定参与转换的列
    var_name=None,  # 转换后列名所在列的名字,默认为 variable
    value_name: Hashable = "value", # 转换后列值所在列的名字,默认为 value
    col_level=None,
    ignore_index: bool = True,
) -> DataFrame:

三、基本使用

python 复制代码
# 使用 id_vars 参数指定不参与转换的列,其余列均进行转换
df1 = pd.melt(frame=df, id_vars="product_id")
print(df1)
复制代码
   product_id variable  value
0           0   store1   95.0
1           1   store1   70.0
2           0   store2  100.0
3           1   store2    NaN
4           0   store3  105.0
5           1   store3   80.0
python 复制代码
# # 使用 id_vars 参数指定不参与转换的列,使用 value_vars 指定参与转换的列,其余列删除
df2 = pd.melt(df, id_vars="product_id", value_vars=["store1", "store2"])
print(df2)
复制代码
   product_id variable  value
0           0   store1   95.0
1           1   store1   70.0
2           0   store2  100.0
3           1   store2    NaN
python 复制代码
# 使用 var_name 和 value_name 修改转换后的列名称
df3 = pd.melt(df, id_vars="product_id", var_name="store", value_name="price")
print(df3)
复制代码
   product_id   store  price
0           0  store1   95.0
1           1  store1   70.0
2           0  store2  100.0
3           1  store2    NaN
4           0  store3  105.0
5           1  store3   80.0
相关推荐
凡人叶枫10 小时前
Effective C++ 条款04:确定对象被使用前已先被初始化
java·linux·开发语言·c++·嵌入式开发
杨运交10 小时前
[030][Web模块]Spring Boot 验证与 OpenAPI 集成实战:从校验规则到文档生成
前端·spring boot·python
培培说证11 小时前
2026财务岗位如何快速提升自身能力
python
小小龙学IT11 小时前
Go 语言后端开发:从并发模型到生产落地的工程实践
开发语言·后端·golang
努力攻坚操作系统11 小时前
编程语言编译运行机制对比:C / Java / Python
java·c语言·python
godspeed_lucip11 小时前
LLM和Agent——专题6:Multi Agent 入门(5)
人工智能·python
ytttr87311 小时前
Qt 数字键盘实现
开发语言·qt
wearegogog12311 小时前
C# .NET 文件比较工具 WinForms
开发语言·c#·.net
再写一行代码就下班11 小时前
Cursor配置Java环境、创建Spring Boot项目的步骤
java·开发语言·spring boot
零陵上将军_xdr11 小时前
后端转全栈学习-Day5-JavaScript 基础-3
开发语言·javascript·学习