python - Pandas:将自定义函数应用于组并将结果存储在每个组的新列中
问题描述
我正在尝试将自定义函数应用于 groupby 对象中的每个组,并将结果存储到每个组本身的新列中。该函数返回 2 个值,我想将这些值分别存储到每组的 2 列中。
我试过这个:
# Returns True if all values in Column1 is different.
def is_unique(x):
status = True
if len(x) > 1:
a = x.to_numpy()
if (a[0] == a).all():
status = False
return status
# Finds difference of the column values and returns the value with a message.
def func(x):
d = (x['Column3'].diff()).dropna()).iloc[0]
return d, "Calculated!"
# is_unique() is another custom function used to filter unique groups.
df[['Difference', 'Message']] = df.filter(lambda x: is_unique(x['Column1'])).groupby(['Column2']).apply(lambda s: func(s))
但我收到错误:'DataFrameGroupBy' object does not support item assignment
我不想重置索引并想使用该get_group
函数查看结果。最终的数据框应如下所示:
df.get_group('XYZ')
-----------------------------------------------------------------
| Column1 | Column2 | Column3 | Difference | Message |
-----------------------------------------------------------------
| 0 A | XYZ | 100 | | |
---------------------------------- | |
| 1 B | XYZ | 20 | 70 | Calculated! |
---------------------------------- | |
| 2 C | XYZ | 10 | | |
-----------------------------------------------------------------
实现此结果的最有效方法是什么?
解决方案
我认为你需要:
def func(x):
d = (x['Column3'].diff()).dropna()).iloc[0]
last = x.index[-1]
x.loc[last, 'Difference'] = d
x.loc[last, 'Message'] = "Calculated!"
return x
df1 = df.filter(lambda x: is_unique(x['Column1']))
df1 = df1.groupby(['Column2']).apply(func)
推荐阅读
- entity-framework - 实体框架最大 ID
- javascript - 使用 Ajax 响应在浏览器中显示 FPDF
- java - 为什么 java 参数在 Windows 和 Linux 中的行为不同?
- asp.net-mvc-5 - 使用 OpenIDConnect 进行 Azure AD 身份验证后无法解决无限循环问题 - 授权码授予
- java - 如何知道是否使用 log4j 正确发送了 syslog 消息而不依赖于异常
- c# - 有什么办法可以隐藏铬硒?
- c# - CS0246: 找不到类型或命名空间名称“系统”
- java - 无法使用 ArrayList 初始化 ArrayAdaper:Java
- reactjs - 为 ubuntu 服务器应用更改的命令
- python - 使用 CreateView 和 forms.Modelform 为 django 模型创建表单的区别?