【问题标题】:group by key with pandas series and export to_dict()与熊猫系列按键分组并导出 to_dict()
【发布时间】:2018-12-29 13:02:09
【问题描述】:

我有一本像这样的字典:

d = {1:0, 2:0, 3:1, 4:0, 5:2, 6:1, 7:2, 8:0} 

我想按我得到的 .keys() 分组:

pandas_ordered = { 0:[1,2,4,8], 1:[3,6], 2:[5,7] }

但是对于

pd.Series(list(d.values())).groupby(list(partition.keys())).to_dict()

下面是一个例子:

# Example:
import pandas as pd

d = {1:0, 2:0, 3:1, 4:0, 5:2, 6:1, 7:2, 8:0} 


def pandas_groupby(dictionary):
   values = list(dictionary.values())
   keys = list(dictionary.keys())
   return pd.Series(values).groupby(keys).to_dict()


pandas_groupby(d)

以上代码产生错误:

AttributeError:无法访问的可调用属性“to_dict” 'SeriesGroupBy' 对象,尝试使用 'apply' 方法

关于如何做到这一点的任何想法?

【问题讨论】:

  • 你必须先agg

标签: pandas pandas-groupby series


【解决方案1】:

您的dict 已经由您的groupby 中的groups 给出

d = {1:0, 2:0, 3:1, 4:0, 5:2, 6:1, 7:2, 8:0} 
s = pd.Series(d)
s.groupby(s).groups

{0: Int64Index([1, 2, 4, 8], dtype='int64'),
 1: Int64Index([3, 6], dtype='int64'),
 2: Int64Index([5, 7], dtype='int64')}

当然,总是可以agg 和自定义

s.groupby(s).agg(lambda x: tuple(x.index)).to_dict()

{0: (1, 2, 4, 8), 1: (3, 6), 2: (5, 7)}

【讨论】:

  • 我应该想到答案会这么简单。谢谢!
猜你喜欢
  • 2016-12-06
  • 2019-11-29
  • 1970-01-01
  • 2017-07-08
  • 1970-01-01
  • 2021-05-07
  • 1970-01-01
  • 2022-07-14
  • 2016-07-07
相关资源
最近更新 更多