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

标签 python numpy group-by splice

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

相关文章:

mysql - MySQL:使用GROUP BY进行中位数查询

python - 如何检测 pdf 文本是否已使用 PyPDF2.extractText 成功提取?

python - Python 中的函数将列表视为全局变量。如何解决这个问题?

python - 与日期的日期时间差 0 秒

python - 使用 numpy.polynomial.legendre 时,如何获得将输入转换为 Legendre 多项式参数的函数?

mysql - 过滤掉MySQL中使用GROUP BY得到的结果

Python 在函数中执行减法

python - 使用单个索引项的 numpy 子矩阵 3D

python - 如何在不使用循环的情况下使用自己的度量创建距离矩阵?

mysql - GROUP 结果值如果为空