首页 > 解决方案 > 我们如何为 numpy nunique 方法应用自定义功能?

问题描述

让我们考虑以下代码,

[sample.csv]
      Name   Year    Status
 1     ABC    2017    200
 2     DEF    2017    404
 3     GHI    2018    404
 4     JKL    2017    500
 5     MNO    2017    200
 6     PQR    2017    301 

预期输出,

没有的总和。唯一记录数从“状态”列计数并按“年”列分组,直接使用“nunique()”,但使用“块”概念(例如,一次 2 条记录)

像往常一样获得否。列的唯一值,

dataset = pd.read_csv(source_file)
dataset.groupby(['year']).nunique()

现在我正在使用以下代码来实现“nunique()”功能,但有时在处理非常大的 CSV 文件(超过 5GB)时它不会返回正确的结果。

import pandas as pd

chunks = pd.read_csv(source_file, chunksize=100000)

data_grp1 = pd.DataFrame() 
for dataset in chunks:
    gb = dataset.groupby(['year'])
    #data_grp1 = gb['status'].nunique() 

    # If we apply the above method/line directly,
    # then our final result would not be correct (it is suitable for only 
    # one shot processing), so I'm using the following lines (Even, 
    # sometimes it is also returns the Incorrect result for large CSV files, 
    # small size files are OK!)

    data_grp1 = pd.concat([data_grp1, gb['status'].unique()])

def nu_fn(x):
    return len(set(np.concatenate(x.values, axis=0)))

res = data_grp1.groupby(['year'], level=0, axis=0)[0].apply(nu_fn)

print(res)

我们如何在不使用内置函数“nunique()”的情况下获得相同的结果?

任何想法,然后请...谢谢!

标签: pythonpandascsvnumpypandas-groupby

解决方案


让我们尝试一些不同的东西,使用pd.factorize

df.groupby('Year')['Status'].apply(lambda x: max(pd.factorize(x)[0]) + 1)

输出:

Year
2017    4
2018    1
Name: Status, dtype: int64

推荐阅读