在 python metpy.units 中无法识别温度的 degC 单位(计算热指数)

问题描述 投票:0回答:1

我正在使用 python 计算热指数(温度、相对湿度)。显示单位错误,这就是为什么我无法计算简单的热指数

将 pandas 导入为 pd 从 metpy.calc 导入 heat_index 来自metpy进口单位

wd = pd.read_csv(""D:/我的数据.csv")

def计算热量指数(温度,R_湿度): 返回 heat_index(温度 * 单位.degC, R_湿度 * 单位.百分比)

t = wd['T2M_MAX'] r = wd['RH2M']

计算热度指数

wd['HI'] = 计算热指数(t, r) 打印(wd.head())

#我的数据结构 LON LAT YEAR MM ... T2M_MIN T2MDEW WS2M_MAX RH2M 0 41.165321 82.919199 2002 1 ... -19.74 -19.19 5.84 98.31 1 41.165321 82.919199 2002 1 ... -19.67 -16.95 7.89 100.00 2 41.165321 82.919199 2002 1 ... -13.06 -12.41 8.36 98.50 3 41.165321 82.919199 2002 1 ... -11.19 -7.88 11.70 96.69 4 41.165321 82.919199 2002 1 ... -7.26 -6.13 10.59 98.88

我想在同一数据中添加 HI 列,并想计算每行的热度指数,

heatmap units-of-measurement heat
1个回答
0
投票

导致 Units 错误的原因是第 3 行的 import 语句。应该是

import pandas as pd 
from metpy.calc import heat_index
from metpy.units import units

导入单位后,您还需要在

calculate_heat_index
函数中考虑两个额外因素:

  1. 您传入
    pd.Series
    (本质上是数据框中的一列)作为
    temperature
    R_humidity
    参数,但是您在
    heat_index
    中调用的
    metpy.calc
    函数对
    pint.Quantity
    对象进行操作.
  2. heat_index
    将返回给您一个
    pint.Quantity
    ,而不是您希望作为新列“HI”附加到数据框的
    pd.Series
    。您的 .csv 似乎需要浮点值,因此您需要使用返回数量中的
    .magnitude
    来去除其单位。

有几种方法可以解决这个问题,要么在调用函数之外打包/解包系列并向其传递单独的温度和相对湿度,要么将该逻辑放在函数内部,以便它整体运行

 Series
在这样的时刻:

def calculate_heat_index(temperatures, rel_humidities):
    result = pd.Series(index=temperatures.keys())
    for k in temperatures.keys():
        result[k] = heat_index(temperatures[k] * units.degC, 
            rel_humidities[k] * units.percent, True).magnitude
    return result

将参数重命名为复数有助于强调这些参数是温度和相对湿度的

Series
。另一个好主意是使用类型注释来强化该函数接受
Series
参数并返回
Series
结果。

传递给

heat_index
的最后一个 bool 参数控制当热指数计算不适用于给定温度时,计算的热指数是否掩盖该值(在结果系列中替换 NaN)。传递 False 将阻止这些 NaN 值出现,尽管我无法判断这是否适用于您的数据集,因为它排除了任何最大温度。

© www.soinside.com 2019 - 2024. All rights reserved.