Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中执行GROUPBY?_Python_Pandas_List_Dictionary_Group By - Fatal编程技术网

如何在python中执行GROUPBY?

如何在python中执行GROUPBY?,python,pandas,list,dictionary,group-by,Python,Pandas,List,Dictionary,Group By,我需要从excel文件中读取数据,然后对数据执行分组 数据的结构如下所示: n c 1 2 1 3 1 4 2 3 2 4 2 5 3 1 3 2 3 3 我需要读取这些数据,然后根据c值生成字典列表。 所需的输出将是一个字典列表,其中c为键,n为值,如下所示: [{1:[3]}, {2:[1,3]}, {3:[1,2,3]}, {4:[1,2]}, {5:[2]}] 我使用此功能读取数据,效果良好: data = pandas.read_excel("pathtofile/filenam

我需要从excel文件中读取数据,然后对数据执行分组
数据的结构如下所示:

n c
1 2
1 3
1 4
2 3
2 4
2 5
3 1
3 2
3 3 
我需要读取这些数据,然后根据c值生成字典列表。 所需的输出将是一个字典列表,其中c为键,n为值,如下所示:

[{1:[3]}, {2:[1,3]}, {3:[1,2,3]}, {4:[1,2]}, {5:[2]}]
我使用此功能读取数据,效果良好:

data = pandas.read_excel("pathtofile/filename.xlsx", header=None)
您可以这样尝试:

d1 = df.groupby('c')['n'].agg(list).to_dict()
res = [{k:v} for k,v in d1.items()]
print(res)
输出:

[{1: [3]}, {2: [1, 3]}, {3: [1, 2, 3]}, {4: [1, 2]}, {5: [2]}]

样本输出
dict

d=df.groupby('c').n.agg(list).to_dict()
{1: [3], 2: [1, 3], 3: [1, 2, 3], 4: [1, 2], 5: [2]}

OT:为什么是一个字典列表,而不是一个包含所有这些键的字典?这个输出结构是另一个函数的输入。但是一本包含所有这些键的字典也可以。谢谢