python - 使用 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))
解决方案
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
类似于transform
iff
返回熊猫系列的行为,这可能是apply
过去为您工作的原因。
有关和之间差异的更深入讨论,请参阅此答案。apply
transform
推荐阅读
- omnet++ - 在 OMNET++ 项目中子类化 INET 模块时出错
- vue.js - Axios 事件处理程序无法在 EventBux 上触发事件
- c++ - 避免竞争条件性能
- linux - 打开一个终端以无限循环结束
- rust - 在 Bevy 游戏引擎中将 1000x1000 像素纹理分配给 SpriteSheetBundle 大约需要 5 秒
- kotlin - android.content.ActivityNotFoundException:没有找到处理 Intent 的活动 { act=android.intent.action.VIEW dat=zhanysch@gmail.com }
- javascript - 从下拉菜单中选择值并将 setCountries() 设置为所选值 - React JS
- c++ - 如何在 Clion IDE 中使用 z3 和 C++?
- python - Django 在模型中按多对多分组
- java - 为什么我看到不请求 Window.FEATURE_SUPPORT_ACTION_BAR?