import numpy as np
from openpyxl import load_workbook
wb = load_workbook('Book1.xlsx')
sheet_1 = wb.get_sheet_by_name('Sheet1')
x1 = np.zeros(sheet_1.max_row)
for i in range(0,sheet_1.max_row):
x1[i]=sheet_1.cell(row=i+1, column=1).value
x2[i] = np.count_nonzero(x1[i])
collections.Counter(x2[i])[0]
我想计算同一列中0的出现次数并将它们加起来并找出excel表中元素的总数。所以结果预期应为3.看起来numpy无法统计。我已经尝试了sum但它只是将数组中的元素相加。感谢你们的任何帮助。
错误消息:TypeError:'numpy.float64'对象不可迭代
Excel表格: 五 五 3 3 4 五 五 0 0 0
答案 0 :(得分:0)
对“计算numpy数组中某个特定数字的出现次数问题的直接解决方案是:
# Note that I cast x1 to np.int because "arr==x" is not reliable with floats
x1=np.array([5,5,3,3,4,5,5,0,0,0],dtype=np.int)
#(x1==0) is boolean array that is True only where 0s are.
#summing that array gives the count of 0s
count_0=np.sum(x1==0)
count_5=np.sum(x1==5)
print("# of 0 : ",count_0)
print("# of 5 : ",count_5)
输出:
# of 0 : 3
# of 5 : 4
使用Counter
的其他解决方案(您似乎正在尝试实施的解决方案)会显示为:
count=collections.Counter(x1)
print("# of 0 : ",count[0])
print("# of 5 : ",count[5])