【问题标题】:Pandas: Checking hourly temperature values which are less than the respective daily thresholdsPandas:检查低于相应每日阈值的每小时温度值
【发布时间】:2021-03-04 20:52:18
【问题描述】:

我只想考虑特定日期的每小时温度值,这些值大于相应的每日阈值,并将其他值替换为 NaN 值。

例如pandas系列值如下

hours = pd.date_range("2018-01-01", periods=120, freq="H")
temperature = pd.Series(range(len(hours)), index=hours)

days = pd.date_range("2018-01-01", periods=5, freq="d")
daily_treshold = pd.Series([5,10,6,25,30], index=days)

现在我想替换第一天小于 5 的每小时温度值,第二天小于 10 的温度值等等。

如何使用 pandas groupby 来实现这一点并应用。谢谢。

【问题讨论】:

  • 也许如果您有groupby(),那么您可以使用zip() 分别与每个组一起工作 - 即for group, temp in zip(groups, [5,10,6,25,30]): ...,然后您可以尝试使用group[ group["temperature"] < temp ] = temp

标签: python pandas pandas-groupby


【解决方案1】:

这是一个易于理解的双循环版本,可以满足您的需求。 pandas.Series.iteritems() 返回 Series 的 (index, value) 元组:

import numpy as np
import pandas as pd

hours = pd.date_range("2018-01-01", periods=120, freq="H")
temperature = pd.Series(range(len(hours)), index=hours)

days = pd.date_range("2018-01-01", periods=5, freq="d")
daily_treshold = pd.Series([5,10,6,25,30], index=days)

for day_index, treshold in daily_treshold.iteritems():
    for hour_index, temp in temperature.iteritems():
        if day_index.date() == hour_index.date():
            if temp < treshold:
                temperature[hour_index] = np.NaN

print(temperature)

使用pandas.Series.apply() 时获取pandas.Series 的索引为impossible。虽然temperaturedaily_treshold 的日期不同,但我们需要做一些更改来比较它们。为方便起见,我将temperature 更改为pandas.Dataframe

这是显示如何在temperature 上使用apply 函数的代码:

import numpy as np
import pandas as pd

hours = pd.date_range("2018-01-01", periods=120, freq="H")

# temperature = pd.Series(range(len(hours)), index=hours)
temperature = pd.DataFrame({'hour': hours,
                            'temp': range(len(hours))})

days = pd.date_range("2018-01-01", periods=5, freq="d")
daily_treshold = pd.Series([5,10,6,25,30], index=days)


def apply_replace(row, daily_treshold):
    treshold = daily_treshold[row['hour'].strftime('%Y-%m-%d')]

    if row['temp'] < treshold:
        return np.NaN
    else:
        return row['temp']

temperature['after_replace'] = temperature.apply(apply_replace, axis=1, args=(daily_treshold,))

【讨论】:

    猜你喜欢
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2022-01-19
    • 2021-09-25
    • 2021-05-22
    • 2022-11-30
    • 2012-10-20
    相关资源
    最近更新 更多