gpt4 book ai didi

在多列上运行的 Python pandas groupby 转换/应用函数

转载 作者:行者123 更新时间:2023-11-28 17:31:51 25 4
gpt4 key购买 nike

尝试使用 apply-split-combine pandas 转换。应用函数需要对多列进行操作。看来我无法使用 pd.transform 让它工作,必须通过 pd.apply 间接进行。有办法做

import pandas as pd
import numpy as np

df = pd.DataFrame({'Date':[1,1,1,2,2,2],'col1':[1,2,3,4,5,6],'col2':[1,2,3,4,5,6]})
col1 = 'col1'
col2 = 'col2'
def calc(dfg):
nparray = np.array(dfg[col1])
somecalc = np.array(dfg[col2])
# do something with somecalc that helps caculate result
return(nparray - nparray.mean()) #just some dummy data, the function does a complicated calculation

#===> results in: KeyError: 'col1'
df['colnew'] = df.groupby('Date')[col1].transform(calc)

#===> results in: ValueError: could not broadcast input array from shape (9) into shape (9,16) or TypeError: cannot concatenate a non-NDFrame object
df['colnew'] = df.groupby('Date').transform(calc)

#===> this works but feels unnecessary
def applycalc(df):
df['colnew'] = calc(df)
return(df)

df = df.groupby('Date').apply(applycalc)

This post是我找到的最接近的。除了存在 groupby 操作之外,我宁愿不将所有列作为单独的参数传递。

编辑:请注意,我并不是真的在尝试计算 nparray - nparray.mean() 这只是一个虚拟计算。它做了一些复杂的事情,返回一个形状为 (group_length,1) 的数组。我还想将 colnew 存储为原始数据框中的新列。

最佳答案

您可以通过然后减法而不是一次进行分组:

In [11]: df["col1"] - df.groupby('Date')["col1"].transform("mean")
Out[11]:
0 -1
1 0
2 1
3 -1
4 0
5 1
dtype: int64

在这种情况下,您不能使用转换,因为该函数返回多个值/数组/系列:

In [21]: def calc2(dfg):
return dfg["col1"] - dfg["col1"].mean()

In [22]: df.groupby('Date', as_index=True).apply(calc2)
Out[22]:
Date
1 0 -1
1 0
2 1
2 3 -1
4 0
5 1
Name: col1, dtype: float64

请注意,返回一个系列很重要,否则它不会对齐:

In [23]: df.groupby('Date').apply(calc)
Out[23]:
Date
1 [-1.0, 0.0, 1.0]
2 [-1.0, 0.0, 1.0]
dtype: object

关于在多列上运行的 Python pandas groupby 转换/应用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33698591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com