gpt4 book ai didi

python - 在 R 中做 dt[,y :=myfun(x), by=list(a,b,c)] 的 pythonic 方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 21:37:29 26 4
gpt4 key购买 nike

假设我有一个包含 x, a, b, c 列的数据框,我想聚合 a, b, c 以获得值 y通过函数 myfun 从 x 的列表中,然后复制每个窗口/分区中所有行的值。

在 R 中的 data.table 这只是 1 行:dt[,y:=myfun(x),by=list(a,b,c)].

在 Python 中,我想到的唯一方法是做这样的事情:

 # To simulate rows in a data frame
class Record:
def __init__(self, x, a, b, c):
self.x = x
self.a = a
self.b = b
self.c = c

# Assume we have a list of Record as df
mykey = attrgetter('a', 'b', 'c')
for key, group_iter in itertools.groupby(sorted(df, key=mykey), key=mykey):
group = list(group_iter)
y = myfun(x.x for x in group)
for x in group:
x.y = y

虽然逻辑很清晰,但我不是百分百满意。有没有更好的方法?

我对pandas不是很熟悉。在这种情况下有帮助吗?

附带问题:我的问题属于哪一类?聚合?分割? window ?这种模式在数据分析中经常出现,因此必须有一个现成的名称。

最佳答案

使用 DataFrame 及其来自 pandasgroupby 方法:

import pandas as pd
df = pd.DataFrame({'a': ['x', 'y', 'x', 'y'],
'x': [1, 2, 3, 4]})

df.groupby('a').apply(myfun)

确切的用法取决于您如何编写函数 myfun。如果使用的列是静态的(例如总是 x),我编写 myfun 以获取函数内的完整 DataFrame 和子集。但是,如果您的函数是为接受向量(或 pandas Series)而编写的,您还可以选择该列并对其应用您的函数:

df.groupby('a')['x'].apply(myfun)

FWIW,当您使用 groupby 时,返回一个 pd.Series 对象通常也很方便。


为了回答您的附带问题,这被称为数据处理的拆分-应用-组合策略。参见 here了解更多信息。

关于python - 在 R 中做 dt[,y :=myfun(x), by=list(a,b,c)] 的 pythonic 方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20433315/

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