【问题标题】:Compare GROUPBY and np.where with Rs datatable package将 GROUPBY 和 np.where 与 Rs 数据表包进行比较
【发布时间】:2021-12-28 14:24:04
【问题描述】:

我正在努力根据带有 groupby 语句的条件在 python 中创建一个新变量。我知道 python 中有一个新的数据表包,但我想探索以下选项。

在 R 中,我做了以下操作:

require(data.table)
id <- c(1,2,3,4,1,5)
units <- c(34, 31, 16, 32, NA, 35)
unitsnew <- c(23, 11, 21, 22, 27, 11)
df = data.table(id, units, unitsnew)
df[, col:= ifelse(is.na(units), min(unitsnew, na.rm = T), units), by = id]

id units unitsnew col
1    34     23    34
2    31     11    31
3    16     21    16
4    32     22    32
1    NA     27    23
5    35     11    35

在 Python 中,

import pandas as pd
import numpy as np
matrix = [(1, 34, 23),
          (2, 31, 11),
          (3, 16, 21),
          (4, 32, 22),
          (1, np.nan, 27),
          (5, 35, 11)]
df = pd.DataFrame(matrix, columns = ['id', 'units', 'unitsnew'])
df.assign(col = np.where(np.isnan(df.units), np.nanmin(df.unitsnew), df.units))

id units unitsnew col
1    34     23    34
2    31     11    31
3    16     21    16
4    32     22    32
1    NA     27    11
5    35     11    35

我不确定在哪里放置 groupby 语句,以便采用每个 id 的最小值。使用R生成所需的输出。在python中,nan值填充为11,因为我未能添加groupby语句。我该如何解决这个问题?谢谢,

【问题讨论】:

    标签: python r pandas


    【解决方案1】:

    首先让我们看看如何使用groupby+transform('min') 获得每组的最小值:

    df.groupby('id')['unitsnew'].transform('min')
    

    输出:

    0    23
    1    11
    2    21
    3    22
    4    23
    5    11
    Name: unitsnew, dtype: int64
    

    现在我们可以在df['units'].isna()时使用where来赋值上面的值:

    df['col'] = df['units'].where(df['units'].notna(),
                                  df.groupby('id')['unitsnew'].transform('min'))
    

    输出:

       id  units  unitsnew   col
    0   1   34.0        23  34.0
    1   2   31.0        11  31.0
    2   3   16.0        21  16.0
    3   4   32.0        22  32.0
    4   1    NaN        27  23.0
    5   5   35.0        11  35.0
    

    【讨论】:

      猜你喜欢
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多