用Python生成数据透视表 – pandas? NumPy的? Xlrd? 来自csv

我一直在寻找几个小时,直到整天如何在Python中生成数据透视表。 我对python很新,所以请忍受我。

我想要的是采取一个csv文件,提取第一列,并使用该列中的数字的数量或频率生成数据透视表,并降序sorting

import pandas import numpy from numpy import recfromtxt a = recfromtxt('1.csv', skiprows=1, usecols=0, delimiter=',') print a 

^我在这里得到的是第一列的列表[2 2 2 6 7]

我需要的是2列的出口

2-3

6–1

7–1

你看过这里吗?

https://pypi.python.org/pypi/pivottable

否则,从你的例子中,你可能只是使用列表parsing:

 >>> l = [2,2,2,6,7] >>> [(i, l.count(i)) for i in set(l)] [ (2,3), (6,1), (7,1) ] 

甚至字典理解,取决于你需要什么:

 >>> l = [2,2,2,6,7] >>> {i:l.count(i) for i in set(l)} { 2: 3, 6: 1, 7: 1 } 

编辑 (来自@Peter DeGlopper的build议)

另一个更有效的方式使用collections.Counter (阅读下面的评论):

 >>> from collections import Counter >>> l = [2,2,2,6,7] >>> Counter(l) Counter({2: 3, 6: 1, 7: 1})