You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中提取DataFrame特定level值并合并至对应行?

DataFrame行重组:匹配RIC值到对应行

原始数据结构

Type             cluster       level          value
0   Accomodation    0-1 € pr.increase   from_price      0.926047
1   Accomodation    0-1 € pr.increase   from_vol        -0.367787
2   Accomodation    0-1 € pr.increase   RIC_from_Vol    561655.141824
3   Accomodation    0-1 € pr.increase   RIC_from_Price  96439.028176
4   Accomodation    1-2 € pr.increase   from_price      1.687742
5   Accomodation    1-2 € pr.increase   from_vol        -0.264432
6   Accomodation    1-2 € pr.increase   RIC_from_Vol    248475.517577
7   Accomodation    1-2 € pr.increase   RIC_from_Price  68894.222423
...

目标数据结构

Type              cluster     level       value            RIC
0   Accomodation    0-1 € pr.increase   from_price  0.926047        96439.028176
1   Accomodation    0-1 € pr.increase   from_vol    -0.367787       561655.141824
4   Accomodation    1-2 € pr.increase   from_price  1.687742        68894.222423
5   Accomodation    1-2 € pr.increase   from_vol    -0.264432       248475.517577
...

解决方案

不需要用unstack,直接通过拆分+匹配合并就能实现需求,步骤如下:

  1. 拆分数据:将原始DataFrame分成两部分,一部分是需要保留的核心行(level为from_price/from_vol),另一部分是存储RIC值的行(level以RIC_开头)。
  2. 调整RIC数据的level列:去掉前缀RIC_,让它和核心行的level名称一一对应。
  3. 合并数据:按Type、cluster、level三个字段合并两部分数据,把RIC值作为新列加入核心行。

具体代码实现:

import pandas as pd

# 假设原始数据存储在df中
# 筛选核心行
main_rows = df[df['level'].isin(['from_price', 'from_vol'])]

# 处理RIC数据:筛选+重命名level+修改列名
ric_rows = df[df['level'].str.startswith('RIC_')].copy()
ric_rows['level'] = ric_rows['level'].str.replace('RIC_', '', regex=False)
ric_rows = ric_rows.rename(columns={'value': 'RIC'})

# 按共同字段合并
final_df = pd.merge(main_rows, ric_rows, on=['Type', 'cluster', 'level'], how='left')

# 可选:如果需要保留原始索引(如示例中的0、1、4、5),则去掉此行
final_df = final_df.reset_index(drop=True)

代码说明

  • 用isin筛选核心行,确保只保留需要展示的level类型;
  • 对RIC行的level做字符串替换,让RIC_from_Vol变成from_vol,实现和核心行的精准匹配;
  • pd.merge的how='left'保证核心行全部保留,不会因为匹配不到RIC值而丢失数据;
  • 如果需要保留原始数据的索引,删除最后一行的reset_index即可。

内容的提问来源于stack exchange,提问作者Silvia Belloro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 03:35:44