Skip to main content
 首页 » 编程设计

python分组拼接: splicing the result returned from itertools. groupby

2024年11月01日10luoye11

我正在尝试使用 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 " " 

我想要的输出是返回第二列 va;ies 的几个数组,这些数组按第一列的值分组,

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

我试图拼接从 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]; 

我还有什么其他想法可以完成这个组然后拼接吗?

谢谢。

请您参考如下方法:

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

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']}