如何基于温湿数组创建单DataFrame列并判断降水类型
单列DataFrame多条件降水类型实现方案
问题说明
需要基于每日更新的温度(TMP)和降水量(precip)数组,生成仅包含降水类型一列的DataFrame,通过多条件判断覆盖更多降水场景(比如温度>32且有降水时为"Rain"、温度较低且降水量大时为"Icing"等)。现有代码错误生成了两列,且条件判断逻辑存在问题。
修正后的完整代码
import pandas as pd import numpy as np # 模拟API获取的温度和降水量数据 TMP = [17, 16, 16, 15, 14, 14, 13, 13, 14, 16, 17, 19, 21, 23, 24, 25, 25, 24, 23, 22, 21, 21, 23, 23] precip = [0.0, 0.0, 0.0, 0.0, 0.017, 0.017, 0.017, 0.017, 0.017,0.017, 0.017, 0.017, 0.017, 0.020, 0.025, 0.035, 0.017, 0.017,0.017, 0.017, 0.017, 0.017, 0.017, 0.02] # 构造包含温度和降水量的基础DataFrame weather_df = pd.DataFrame({ 'Temperature': TMP, 'Precipitation': precip }) # 定义多条件规则和对应结果 conditions = [ # 温度>32且降水量>0 → Rain (weather_df['Temperature'] > 32) & (weather_df['Precipitation'] > 0), # 温度<32且降水量>0.25 → Icing (weather_df['Temperature'] < 32) & (weather_df['Precipitation'] > 0.25), # 降水量<0.001 → Dry (weather_df['Precipitation'] < 0.001), # 其他小降水情况 → Light Rain (weather_df['Precipitation'] >= 0.001) & (weather_df['Precipitation'] <= 0.25) ] results = ['Rain', 'Icing', 'Dry', 'Light Rain'] # 生成降水类型列 weather_df['Precipitation_Type'] = np.select(conditions, results, default='Unknown') # 提取仅包含降水类型的目标DataFrame weather_df2 = weather_df[['Precipitation_Type']] # 样式设置函数 def make_pretty(styler): styler.set_caption("Weather Conditions") # 给不同降水类型设置差异化背景色 styler.applymap(lambda x: 'background-color: #90EE90' if x == 'Dry' else 'background-color: #87CEFA' if x == 'Rain' else 'background-color: #ADD8E6' if x == 'Light Rain' else 'background-color: #FFB6C1' if x == 'Icing' else '', subset=['Precipitation_Type']) return styler # 应用样式并展示 s = weather_df2.style.pipe(make_pretty) s
关键修正点说明
- DataFrame构造:原代码将整个数组作为单个单元格值,改为直接将数组传入,生成对应行数的标准DataFrame。
- 多条件判断:用
np.select替代循环判断,批量处理所有行,避免原函数中循环仅执行一次就返回的问题,同时方便扩展更多条件规则。 - 单列输出:通过筛选
Precipitation_Type列,得到仅包含目标数据的weather_df2。 - 样式优化:针对分类类型的降水数据,替换原代码中不匹配的数值渐变样式,改为按类型设置背景色,更直观展示结果。
内容的提问来源于stack exchange,提问作者Justyna
相关产品推荐
相关产品推荐

