如何在 pivot_table 之后对 Dask 中的索引进行排序

How to sort index in Dask following pivot_table

尝试在 dask 中使用 pivot_table,同时维护排序索引。我有一个简单的 pandas 数据框,看起来像这样:

# make dataframe, fist in pandas and then in dask
df = pd.DataFrame({'A':['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'], 'B': ['a', 'b', 'c', 'a', 'b', 'c', 'a','b', 'c'], 'dist': [0, .1, .2, .1, 0, .3, .4, .1,  0]})

df.sort_values(by='A', inplace=True)
dd = dask.dataframe.from_pandas(df, chunksize=3)  # just for demo's sake, you obviously don't ever want a chunksize of 3
print(dd.known_divisions)  # Here I get True, which means my data is sorted

# now pivot and see if the index remains sorted
dd = dd.categorize('B')
pivot_dd = dd.pivot_table(index='A', columns='B', values='dist')
print(pivot_dd.known_divisions) # Here I get False, which makes me sad

我很想找到一种方法让 pivot_dd 有一个排序索引,但我在 dask 中没有看到 sort_index 方法并且无法将 'A' 设置为index w/out 出现键错误(它已经是索引了!)。

在这个玩具示例中,我可以先旋转 pandas table,然后再排序。我想到的实际应用程序不允许我这样做。

提前感谢任何help/suggestions。

这可能不是您想要的,甚至可能不是最佳答案,但它似乎确实有效。第一个问题是 pivot 操作为列创建了一个分类索引,这很烦人。您可以执行以下操作。

>>> pivot_dd = dd.pivot_table(index='A', columns='B', values='dist')
>>> pivot_dd.columns = list(pivot_dd.columns)
>>> pivot_dd = pivot_dd.reset_index().set_index('A', sorted=True)
>>> pivot_dd.known_divisions
True