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

2024-05-20 15:01:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下图像: 请参考一下。在

http://i58.tinypic.com/33219hh.png

我想要的是让代码读取每个值 在每一列中,告诉我这个“数字”和 “字母”在那一栏里。换句话说,什么是 “数字”和“字母”分别出现在各自的栏中?在

这是我的代码:

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。 但是,我想知道如何同时阅读上面提到的所有东西 前面提到的。在


Tags: 代码in图像httpforws字母extract
3条回答

将每列输入^{}

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})
>>> 

您可以查看pandas。解决方案可以是这样的:

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

请尝试为每一列使用词典:

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]

相关问题 更多 >