这是一个易于理解的双循环版本,可以满足您的需求。 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。虽然temperature 和daily_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,))