我正在尝试使用 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];
我还有其他想法如何完成这个组然后拼接吗?
谢谢。
最佳答案
我认为你正在尝试这样做:
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']}
关于Python分组和拼接: splicing the result returned from itertools. groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17561830/