【问题标题】:GroupBy results to dictionary of listsGroupBy 结果到列表字典
【发布时间】:2015-07-04 18:02:26
【问题描述】:

我有一个看起来像这样的 excel 表:

Column1 Column2 Column3
0       23      1
1       5       2
1       2       3
1       19      5
2       56      1
2       22      2
3       2       4
3       14      5
4       59      1
5       44      1
5       1       2
5       87      3

我希望提取该数据,按第 1 列对其进行分组,然后将其添加到字典中,使其如下所示:

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

这是我目前的代码

excel = pandas.read_excel(r"e:\test_data.xlsx", sheetname='mySheet', parse_cols'A,C')
myTable = excel.groupby("Column1").groups
print myTable

但是,我的输出如下所示:

{0: [0L], 1: [1L, 2L, 3L], 2: [4L, 5L], 3: [6L, 7L], 4: [8L], 5: [9L, 10L, 11L]}

谢谢!

【问题讨论】:

    标签: python pandas xlrd


    【解决方案1】:

    您可以在Column1groupby,然后将Column3 转至apply(list) 并致电to_dict

    In [81]: df.groupby('Column1')['Column3'].apply(list).to_dict()
    Out[81]: {0: [1], 1: [2, 3, 5], 2: [1, 2], 3: [4, 5], 4: [1], 5: [1, 2, 3]}
    

    或者,做

    In [433]: {k: list(v) for k, v in df.groupby('Column1')['Column3']}
    Out[433]: {0: [1], 1: [2, 3, 5], 2: [1, 2], 3: [4, 5], 4: [1], 5: [1, 2, 3]}
    

    【讨论】:

    • 当@EdChum's 相同并且在 3 分钟前发布时,意味着接受这个答案。
    • 对多个特性执行此操作的最佳方式是什么字典。
    • 哇,你的名字应该是英雄而不是零
    【解决方案2】:

    根据the docsGroupBy.groups

    是一个字典,其键是计算的唯一组和对应的 values 是属于每个组的 轴标签

    如果你想要值本身,你可以groupby 'Column1' 然后调用apply 并传递list 方法来应用到每个组。

    然后您可以根据需要将其转换为字典:

    In [5]:
    
    dict(df.groupby('Column1')['Column3'].apply(list))
    Out[5]:
    {0: [1], 1: [2, 3, 5], 2: [1, 2], 3: [4, 5], 4: [1], 5: [1, 2, 3]}
    

    (注意:请查看this SO question,了解为什么数字后面跟着L

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      • 2016-12-06
      • 2011-02-15
      • 2021-02-21
      • 1970-01-01
      相关资源
      最近更新 更多