I am a beginner struggling with Python every day. I have a large data set that has Name of animals in the 2nd column. I have a program to add up the count of each animal by its name (each row has 1 animal Name and 1 “count” data). I am trying to get the sum of those count data I obtained using Python but I am not being able to do that. The code I have so far is:
import csv, collections
reader=csv.reader(open('C:\Users\Owl\Data.txt','rb'), delimiter='\t')
counts=collections.Counter()
for line in reader:
Name=line[1]
counts[Name]+=1
for (Name, count) in sorted(counts.iteritems()):
Output=list('%s' % count) #Make output string to a list
Sum=sum(Output) # Sum function requires a list
print 'Total kinds of Animals: %s' % Sum
I get an error saying " File "sum_count.py", line 17, in <module> Sum=sum(Output) # Sum function requires a list TypeError: unsupported operand type(s) for +: 'int' and 'str'".
What I have figured out so far is that because sum apparently require the input type to be a list, I converted the count data (which was string) to a list but when I do Output=list('%s' % count), it seems that all the count data that are more than 2 digits are split. For example, when I print Output, it will be like this:
['1', '6', '3']
['3']
['1', '8', '5', '9']
['7', '9']
instead of
['163']
['3']
['1859']
['79']
What I want to do here is to get a single “sum” of these elements. Here, it will be 4. Four kinds of animals.
I am thinking that this may be the reason why I am getting the error above. I might be wrong but could somebody please help me how to solve this issue? Thank you for your help in advance!
I don’t think you need to use
sum.Try this:
Or, possibly better:
sumis for when you have a list of numbers and want to find the sum of that list of numbers.You have already collected the sum number of each animal using
counts— you just need to display it.Edit
To sum up the total number of animals counted, you can do this:
Edit 2
The number of kinds of animals counted is simply the length of the
countsdictionary: