【问题标题】:How to sort index in Dask following pivot_table如何按照 pivot_table 在 Dask 中对索引进行排序
【发布时间】:2018-04-16 19:47:28
【问题描述】:

尝试在 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”设置为索引而不会出现关键错误(它已经是索引了!)。

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

提前感谢您的任何帮助/建议。

【问题讨论】:

    标签: python pandas indexing pivot-table dask


    【解决方案1】:

    这可能不是您想要的,甚至可能不是最好的答案,但它似乎确实有效。第一个问题是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
    

    【讨论】:

      猜你喜欢
      • 2017-04-28
      • 1970-01-01
      • 2014-10-31
      • 1970-01-01
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      相关资源
      最近更新 更多