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

Python pandas风速时序数据转涡轮机功率输出报错解决

问题分析与修正方案

错误根源

  • apply参数错误:你调用df_ws.power_production_Vestas.apply(conv_test)时,传入函数的x是该列的单个浮点数,不是DataFrame的行,所以x['wind_speed_hh']会触发'float' object is not subscriptable错误。
  • 条件逻辑错误:第一个条件4 <= x['wind_speed_hh']会覆盖所有大于等于4的情况,后面的elif永远不会执行,逻辑顺序完全颠倒。
  • 系数取值错误:weight_vestas['wv1']返回的是Series而非单个数值,直接相乘会导致类型不匹配。
  • 列名引用错误:函数里的x['df_ws.wind_speed_hh']是无效列名,不存在这个字段。

修正后的代码

方案1:修正函数并正确调用

import pandas as pd
time = pd.date_range(start='2019-01-06 20:00:00', end='2019-01-07 03:00:00', freq='H')

df_ws = pd.DataFrame({"wind_speed_hh": 
                   [3.359367, 2.695838, 3.036351, 6.64743,
                    9.93, 13.13, 15.574893, 17.3432]}, index = time)

# 转换系数改用字典,直接取标量值更方便
weight_vestas = {
    "wv1": 0.0,   # 风速<4
    "wv2": 0.2,   # 4<=风速<6
    "wv3": 0.5,   # 6<=风速<8
    "wv4": 1.4,   # 8<=风速<10
    "wv5": 2.6,   # 10<=风速<12
    "wv6": 3.0,   # 12<=风速<14
    "wv7": 3.0,   # 14<=风速<16
    "wv8": 3.0    # 风速>=16
}

def conv_test(wind_speed):
    if wind_speed < 4:
        return weight_vestas["wv1"] * wind_speed
    elif 4 <= wind_speed < 6:
        return weight_vestas["wv2"] * wind_speed
    elif 6 <= wind_speed < 8:
        return weight_vestas["wv3"] * wind_speed
    elif 8 <= wind_speed < 10:
        return weight_vestas["wv4"] * wind_speed
    elif 10 <= wind_speed < 12:
        return weight_vestas["wv5"] * wind_speed
    elif 12 <= wind_speed < 14:
        return weight_vestas["wv6"] * wind_speed
    elif 14 <= wind_speed < 16:
        return weight_vestas["wv7"] * wind_speed
    elif wind_speed >= 16:
        return weight_vestas["wv8"] * wind_speed
    return 0.0

# 对风速列应用函数,赋值给目标列
df_ws['power_production_Vestas'] = df_ws['wind_speed_hh'].apply(conv_test)
print(df_ws)

方案2:用pd.cut实现向量化运算(推荐)

避免循环,用pandas原生向量化方法,性能更优:

import pandas as pd
time = pd.date_range(start='2019-01-06 20:00:00', end='2019-01-07 03:00:00', freq='H')

df_ws = pd.DataFrame({"wind_speed_hh": 
                   [3.359367, 2.695838, 3.036351, 6.64743,
                    9.93, 13.13, 15.574893, 17.3432]}, index = time)

# 定义风速区间和对应系数
bins = [-float('inf'), 4, 6, 8, 10, 12, 14, 16, float('inf')]
coefficients = [0.0, 0.2, 0.5, 1.4, 2.6, 3.0, 3.0, 3.0]

# 为每个风速匹配对应系数
df_ws['coefficient'] = pd.cut(df_ws['wind_speed_hh'], bins=bins, labels=coefficients)
# 计算功率输出
df_ws['power_production_Vestas'] = df_ws['wind_speed_hh'] * df_ws['coefficient'].astype(float)

# 可删除中间系数列
df_ws.drop('coefficient', axis=1, inplace=True)
print(df_ws)

关键修正点

  • 转换系数改用字典(或从原DataFrame提取标量值),避免Series带来的类型问题。
  • 对wind_speed_hh列应用函数,传入单个风速值而非整行/其他列。
  • 调整条件判断顺序,从低到高覆盖所有区间,避免逻辑覆盖。
  • 优先使用pd.cut向量化方法,处理大数据量时效率远高于循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:30:56