【发布时间】: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语句。我该如何解决这个问题?谢谢,
【问题讨论】: