【问题标题】:Groupby and apply pandas vs daskGroupby 并应用 pandas vs dask
【发布时间】:2017-12-19 19:46:41
【问题描述】:

我对@9​​87654322@ 的行为有些不理解。假设我想从熊猫复制这个

import pandas as pd
import dask.dataframe as dd
import random

s = "abcd"
lst = 10*[0]+list(range(1,6))
n = 100
df = pd.DataFrame({"col1": [random.choice(s) for i in range(n)],
                   "col2": [random.choice(lst) for i in range(n)]})
# I will need an hash in dask
df["hash"] = 2*df.col1
df = df[["hash","col1","col2"]]

def fun(data):
    if data["col2"].mean()>1:
        data["col3"]=2
    else:
        data["col3"]=1
    return(data)

df1 = df.groupby("col1").apply(fun)
df1.head()

返回

  hash col1  col2  col3
0   dd    d     0     1
1   aa    a     0     2
2   bb    b     0     1
3   bb    b     0     1
4   aa    a     0     2

在 Dask 我试过了

def fun2(data):
    if data["col2"].mean()>1:
        return 2
    else:
        return 1

ddf = df.copy()
ddf.set_index("hash",inplace=True)
ddf = dd.from_pandas(ddf, npartitions=2)

gpb = ddf.groupby("col1").apply(fun2, meta=pd.Series())

其中 groupby 导致与 pandas 相同的结果,但我很难将结果合并到保留哈希索引的新列上。 我想得到以下结果

      col1  col2  col3
hash           
aa      a     5     2
aa      a     0     2
aa      a     0     2
aa      a     0     2
aa      a     4     2

更新

玩合并我找到了这个解决方案

ddf1 = dd.merge(ddf, gpb.to_frame(), 
                left_on="col1",
                left_index=False, right_index=True)
ddf1 = ddf1.rename(columns={0:"col3"})

如果我必须对几列进行分组,我不确定这将如何工作。 Plus 并不优雅。

【问题讨论】:

标签: python pandas group-by apply dask


【解决方案1】:

使用join怎么样?

这是您的 dask 代码,但将系列命名为 pd.Series(name='col3')

def fun2(data):
    if data["col2"].mean()>1:
        return 2
    else:
        return 1

ddf = df.copy()
ddf.set_index("hash",inplace=True)
ddf = dd.from_pandas(ddf, npartitions=2)

gpb = ddf.groupby("col1").apply(fun2, meta=pd.Series(name='col3'))

然后加入

ddf.join(gpb.to_frame(), on='col1')
print(ddf.compute().head())
      col1  col2  col3
hash                 
cc      c     0     2
cc      c     0     2
cc      c     0     2
cc      c     2     2
cc      c     0     2

【讨论】:

  • 首先感谢您的回答。使用 meta 从 pandas 转移仍然是我想要弄清楚的事情。你的解决方案比我的快,我很高兴。我接受您的解决方案,我将在多个列上询问关于 groupby 的另一个问题。
猜你喜欢
  • 2018-10-31
  • 1970-01-01
  • 2018-01-08
  • 2014-11-29
  • 2020-05-09
  • 1970-01-01
  • 2022-12-27
  • 2022-08-06
  • 2020-11-19
相关资源
最近更新 更多