【问题标题】:Replace NaNs of a categorical variable by grouping them with respect to continuous variable通过对连续变量进行分组来替换分类变量的 NaN
【发布时间】:2021-09-26 06:10:05
【问题描述】:

我在根据“温度”对“天气条件”进行分组时遇到问题,因为它是一个连续变量。所以,我需要通过将“温度”转换为int64,然后替换“Weather cond”的 (by mode) NaN 来对它进行分组。但它不应该将原始的“温度”转换为int64。

Df 是:

temperature weather cond
    0   25.6    Cloudy
    1   28.7    Sunny
    2   26.9    NaN
    3   25.9    Cloudy
    4   29.9    Cloudy
    5   28.1    Overcast
    6   34.7    Sunny
    7   29.6    NaN
    8   26.6    NaN
    9   20.5    NaN

解释:

如果我们考虑温度 28.7 和 28.1,这些值应转换为 28(不在原始 df 中),然后用代表这些温度的“天气条件”模式填充 NaN。

注意:即使是近似值(地板/天花板)也可以接受,即将 28.7 视为 29,将 28.1 视为 28。

【问题讨论】:

  • Sunny 有 1 34 和 1 28。在这种情况下,您如何确定模式。
  • 另外你是什么意思替换模式?模式是'Cloudy' -> 25, 'Overcast' -> 28, 'Sunny' -> 28/34 但缺失值是26,29,26,20 那么映射是如何发生的呢?
  • @HenryEcker 我在这里使用模式,因为天气条件对于特定温度不是固定的,它可能会有所不同。
  • @HenryEcker 如果某些天气条件没有任何温度,您可以使用更接近的温度来处理。
  • 所以你想用温度模式的值填充天气条件的NaN?

标签: python pandas nan continuous dtype


【解决方案1】:
import io
df = pd.read_csv(io.StringIO("""temperature  weather cond
    0   25.6    Cloudy
    1   28.7    Sunny
    2   26.9    NaN
    3   25.9    Cloudy
    4   29.9    Cloudy
    5   28.1    Overcast
    6   34.7    Sunny
    7   29.6    NaN
    8   26.6    NaN
    9   20.5    NaN"""), sep="\s\s+", engine="python")

pd.merge_asof(df.sort_values("temperature"), 
              df.loc[~df["weather cond"].isna()].sort_values("temperature"), 
              on="temperature", 
              direction="nearest")

temperature weather cond_x weather cond_y
0 20.5 nan Cloudy
1 25.6 Cloudy Cloudy
2 25.9 Cloudy Cloudy
3 26.6 nan Cloudy
4 26.9 nan Cloudy
5 28.1 Overcast Overcast
6 28.7 Sunny Sunny
7 29.6 nan Cloudy
8 29.9 Cloudy Cloudy
9 34.7 Sunny Sunny

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-01
    • 2017-09-09
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    相关资源
    最近更新 更多