我有以下数据集:
location category percent
A 5 100.0
B 3 100.0
C 2 50.0
4 13.0
D 2 75.0
3 59.0
4 13.0
5 4.0
我正在尝试获取数据框中按位置分组的最大类别项目。即,如果我想要每组的前 2 个最大百分比,则输出应该是:
location category percent
A 5 100.0
B 3 100.0
C 2 50.0
4 13.0
D 2 75.0
3 59.0
看起来在 pandas 中这是相对直接使用的pandas.core.groupby.SeriesGroupBy.nlargest
但 dask 没有nlargest
groupby 的函数。一直在玩apply
但似乎无法让它正常工作。
df.groupby(['location'].apply(lambda x: x['percent'].nlargest(2)).compute()
但我刚刚收到错误ValueError: Wrong number of items passed 0, placement implies 8
apply 应该可以工作,但是你的语法有点不对:
In [11]: df
Out[11]:
Dask DataFrame Structure:
Unnamed: 0 location category percent
npartitions=1
int64 object int64 float64
... ... ... ...
Dask Name: from-delayed, 3 tasks
In [12]: df.groupby("location")["percent"].apply(lambda x: x.nlargest(2), meta=('x', 'f8')).compute()
Out[12]:
location
A 0 100.0
B 1 100.0
C 2 50.0
3 13.0
D 4 75.0
5 59.0
Name: x, dtype: float64
在熊猫中你会有.nlargest
and .rank
作为 groupby 方法,您可以在不应用的情况下执行此操作:
In [21]: df1
Out[21]:
location category percent
0 A 5 100.0
1 B 3 100.0
2 C 2 50.0
3 C 4 13.0
4 D 2 75.0
5 D 3 59.0
6 D 4 13.0
7 D 5 4.0
In [22]: df1.groupby("location")["percent"].nlargest(2)
Out[22]:
location
A 0 100.0
B 1 100.0
C 2 50.0
3 13.0
D 4 75.0
5 59.0
Name: percent, dtype: float64
dask 文档说明 http://dask.pydata.org/en/latest/dataframe-overview.html#scope:
Dask.dataframe 涵盖了 pandas API 的一小部分但经常使用的部分。
这种限制有两个原因:
- pandas API 非常庞大
- 有些操作确实很难并行执行(例如排序)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)