python - 我们如何为 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()”的情况下获得相同的结果?
任何想法,然后请...谢谢!
解决方案
让我们尝试一些不同的东西,使用pd.factorize
:
df.groupby('Year')['Status'].apply(lambda x: max(pd.factorize(x)[0]) + 1)
输出:
Year
2017 4
2018 1
Name: Status, dtype: int64
推荐阅读
- javascript - 反应路由器,在 router.js 中使用路由器道具
- artificial-intelligence - Dialogflow V2:使用 detect_intent 附加用户元数据
- python - 我应该在 Django 中以哪种方式使用外键
- javascript - JS数组长度为空时返回1而不是0
- java - 如何从字符串中解析字符?
- terraform - 如何从 terraform 上的不同订阅导入托管服务标识
- python - Spark 和 Python 的协方差和相关性失败
- verilog - icarus verilog 中的多维数组端口支持
- python - 如何更改matplotlib pyplot中的图例元素?
- mysql - MySQL 5.7 上的存储过程语法无效,但适用于 MariaDB