在维护排序索引的同时尝试在dask中使用ivot_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具有排序的索引,但是我没有sort_index
在dask中看到一个方法,并且无法将'A'设置为没有关键错误的索引(它已经是索引!) 。
在这个玩具示例中,我可以先旋转熊猫表,然后再排序。我想到的真正的应用程序不允许我这样做。
在此先感谢您的帮助/建议。
这可能不是您想要的,甚至可能不是最佳答案,但它确实起作用了。第一个难题是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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句