通过应用Python熊猫更快地进行分组?

时间:2020-03-07 06:34:19

标签: python pandas pandas-groupby pandas-apply

如何使Groupby Apply运行更快,或者如何以其他方式编写它?

import numpy as np
import pandas as pd

df = pd.DataFrame({'ID':[1,1,1,1,1,2,2,2,2,2],\
                   'value':[1,2,np.nan,3,np.nan,1,2,np.nan,4,np.nan]})

result = df.groupby("ID").apply(lambda x: len(x[x['value'].notnull()].index)\
                    if((len(x[x['value']==1].index)>=1)&\
                    (len(x[x['value']==4].index)==0)) else 0)

输出:

Index  0  
1      3  
2      0

我的程序现在运行非常慢。我可以更快吗?过去我在使用groupby()之前已进行了过滤,但是在这种情况下我看不到一种简单的方法。

1 个答案:

答案 0 :(得分:1)

不确定这是否是您所需要的。我已经对其进行了分解,但是您可以轻松地对其进行方法链接以使代码更紧凑:

df = pd.DataFrame(
    {
        "ID": [1, 1, 1, 1, 1, 2, 2, 2, 2, 2],
        "value": [1, 2, np.nan, 3, np.nan, 1, 2, np.nan, 4, np.nan],
    }
)

df["x1"] = df["value"] == 1
df["x2"] = df["value"] == 4

df2 = df.groupby("ID").agg(
    y1=pd.NamedAgg(column="x1", aggfunc="max"),
    y2=pd.NamedAgg(column="x2", aggfunc="max"),
    cnt=pd.NamedAgg(column="value", aggfunc="count"),
)

df3 = df2.assign(z=lambda x: (x['y1'] & ~x['y2'])*x['cnt'])

result = df3.drop(columns=['y1', 'y2', 'cnt'])
print(result)

将会产生

    z
ID   
1   3
2   0