【问题标题】:Python group and splice: splicing the result returned from itertools.groupbyPython分组和拼接:拼接从itertools.groupby返回的结果
【发布时间】:2013-07-10 03:06:28
【问题描述】:

我正在尝试使用 numpy genfromtxt 将 csv 文件读取到结构化数组中。我计划对其进行排序,然后使用 groupby 根据其中一列的字符串值将文件分成组。最后,我将拼接每个组中的列以进行额外处理。

这是一个小例子,我想为每个组返回一个特定的列。

import numpy as np
from itertools import groupby

food1 = [[" vegetable", "tomato"], [" vegetable", "spinach"], [" fruit", "watermelon"], [" fruit", "grapes"], [" meat", "beef"]]

for key, group in groupby(food1, lambda x: x[0]):
    print key   
    group[:1]
# In the line above, TypeError: 'itertools._grouper' object is unsubscriptable, I have tried it with  food1 or food2
    for thing in group:     
        print key + ": "  + thing[1];       
    print " "

我想要的输出是返回由第一列值分组的第二列变量的几个数组,

所以 蔬菜:[“番茄”,“菠菜”], 水果:[“西瓜”、“葡萄”] ...等

我尝试从 groupby 拼接返回的组,但由于它是一个迭代器,我会得到 TypeError: 'itertools._grouper' object is unsubscriptable。

我知道我可以拼接从 genfromtxt 加载的数据,但它是先分组然后拼接的组合给我带来了麻烦。

data = np.genfromtxt("file.txt", delimiter=',', skiprows=3)
# splicing a column from the ndarray read from the csv file
column2 = data[:,2];

任何其他想法我如何才能完成这个组然后拼接?

谢谢。

【问题讨论】:

    标签: python numpy group-by splice


    【解决方案1】:

    我认为您正在尝试这样做:

    from itertools import groupby
    
    food1 = [[" vegetable", "tomato"], [" vegetable", "spinach"], [" fruit", "watermelon"], [" fruit", "grapes"], [" meat", "beef"]]
    
    data={}
    for key, group in groupby(sorted(food1), key=lambda x: x[0]):
        data[key.strip()]=[v[1] for v in group]
    

    然后数据是:

    {'vegetable': ['tomato', 'spinach'], 
     'fruit': ['watermelon', 'grapes'], 
     'meat': ['beef']}
    

    【讨论】:

    • 谢谢,这行得通。对我的另一个问题的回答也导致了另一种对值进行分组并选择列而不使用 groupby stackoverflow.com/questions/17560879/…
    • 分组前最好对列表进行排序;否则,您将丢失一些物品。您可以使用以下代码对列表进行排序: food1.sort(key=lambda x: x[0])
    • @user2720402:确实。更正了
    猜你喜欢
    • 1970-01-01
    • 2012-04-14
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多