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

如何为长格式DataFrame添加基于Variable列的Phase分箱列?

基于Variable列显式生成Phase新列的实现方案

原始数据表

WellDateTypeVariableValue
A1/1/2023currentOil_Fcst20
A1/2/2023currentOil_Fcst100
A1/1/2023prevOil_Fcst_Prev25
A1/2/2023prevOil_Fcst_Prev50
A1/1/2023currentGas_Fcst50
A1/2/2023currentGas_Fcst100
A1/1/2023prevGas_Fcst_Prev25
A1/2/2023prevGas_Fcst_Prev50

目标数据表

WellDateTypeVariableValuePhase
A1/1/2023currentOil_Fcst20Oil
A1/2/2023currentOil_Fcst100Oil
A1/1/2023prevOil_Fcst_Prev25Oil
A1/2/2023prevOil_Fcst_Prev50Oil
A1/1/2023currentGas_Fcst50Gas
A1/2/2023currentGas_Fcst100Gas
A1/1/2023prevGas_Fcst_Prev25Gas
A1/2/2023prevGas_Fcst_Prev50Gas

完全可以基于Variable列的取值显式定义Phase新列,以下是不同工具下的实现方法:

1. Python(Pandas)实现

两种常用方法,按需选择:

  • 方法1:通过字符串包含判断赋值
import pandas as pd
import numpy as np

# 构造原始数据
df = pd.DataFrame({
    'Well': ['A']*8,
    'Date': ['1/1/2023', '1/2/2023']*4,
    'Type': ['current', 'current', 'prev', 'prev']*2,
    'Variable': ['Oil_Fcst', 'Oil_Fcst', 'Oil_Fcst_Prev', 'Oil_Fcst_Prev', 'Gas_Fcst', 'Gas_Fcst', 'Gas_Fcst_Prev', 'Gas_Fcst_Prev'],
    'Value': [20, 100, 25, 50, 50, 100, 25, 50]
})

# 生成Phase列
df['Phase'] = np.where(df['Variable'].str.contains('Oil'), 'Oil', 'Gas')
  • 方法2:提取变量前缀(下划线分隔的首段)
# 提取Variable列下划线前的内容作为Phase值
df['Phase'] = df['Variable'].str.split('_').str[0]

2. Excel实现

在F2单元格输入以下任一公式,下拉填充即可:

  • 基于字符串匹配
=IF(ISNUMBER(SEARCH("Oil",D2)),"Oil","Gas")
  • 提取前缀
=LEFT(D2,FIND("_",D2)-1)

3. SQL实现

如果数据存储在数据库中,使用CASE语句生成新列:

SELECT 
    Well,
    Date,
    Type,
    Variable,
    Value,
    CASE 
        WHEN Variable LIKE '%Oil%' THEN 'Oil'
        WHEN Variable LIKE '%Gas%' THEN 'Gas'
        ELSE NULL -- 可选:处理未匹配的特殊情况
    END AS Phase
FROM your_table;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 23:35:25