用 pandas 系列按键分组并导出到_dict()

问题描述 投票:0回答:2

我有一本看起来像这样的字典:

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' 方法

关于如何做到这一点有什么想法吗?

pandas pandas-groupby series
2个回答
0
投票

dict
已经被你的
groups
里的
groupby

给了
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)}

0
投票
    pd.Series({1:0, 2:0, 3:1, 4:0, 5:2, 6:1, 7:2, 8:0},name='col1').reset_index()
.groupby("col1").agg(list)['index'].to_dict()

输出:

{0: [1, 2, 4, 8], 1: [3, 6], 2: [5, 7]}
© www.soinside.com 2019 - 2024. All rights reserved.