首页 > 解决方案 > 使用 Groupby 和 np.where 时,Pandas 应用与变换

问题描述

我正在我的数据框中创建一系列计算,并且一直在成功使用 apply,直到下面的一个示例。谁能解释为什么“转换”在这种情况下有效而“应用”无效?我一直在用apply成功地进行加减运算,所以新的方面是np.where。

它不会抛出错误,它只是返回列的 NaN。

我能找到的适用地址的文章都不应该有这种限制。有很多信息表明变换应该更具限制性,即一次只处理一列,并被迫返回与序列长度相等的值数量。

df['val'] = compiled.groupby(['category']).B.apply(lambda x : np.where(x > 0, x, 0))

df['val'] = compiled.groupby(['category']).B.transform(lambda x : np.where(x > 0, x, 0))

标签: pythonpandasnumpy

解决方案


df.groubby('cagegory').V.apply(f),当f返回一个 numpy 数组时,将返回一个数据框,每个类别一个项目:

import numpy as np
import pandas as pd
np.random.seed(1701)
df = pd.DataFrame({
    'category': ['A', 'A', 'A', 'B', 'B', 'B'],
    'B': np.random.randn(6)
})
df.groupby('category').B.apply(lambda x : np.where(x > 0, x, 0))
# category
# A    [0.0, 2.3759516516254156, 0.0]
# B                   [0.0, 0.0, 0.0]
# Name: B, dtype: object

df.groubby('cagegory').V.transform(f),当f返回一个 numpy 数组时,将返回一个数据帧,在原始数据帧中每行一个项目:

df.groupby('category').B.transform(lambda x : np.where(x > 0, x, 0))
# 0    0.000000
# 1    2.375952
# 2    0.000000
# 3    0.000000
# 4    0.000000
# 5    0.000000
# Name: B, dtype: float64

由于您将结果分配给原始数据框中的列,因此transform是合适的方法。

请注意, 的行为apply类似于transformiff返回熊猫系列的行为,这可能是apply过去为您工作的原因。

有关和之间差异的更深入讨论,请参阅此答案applytransform


推荐阅读