I have two variables – animals
and food
; if I print them they look like
var1 var2
pig acorn
pig acorn
pig carrot
pig potato
pig acorn
pig carrot
dog meat
dog acorn
dog carrot
dog potato
dog carrot
dog meat
cat meat
cat fish
cat carrot
cat potato
and so on...
I want this data to be stored in a new CSV file in the following format (but can't figure out how to do it):
animals food count
pig acorn 15
pig carrot 7
pig potato 10
dog acorn 2
dog meat 10
dog potato 1
and so on...
In other words, I want the observation in the animals
variable to reoccur exactly as many times as there are different types of items in the food
variable, and place the aggregated score in a new variable. E.g, if there are 50 occurrences of pig
, 30 of which are acorn
, 10 of which are carrot
and 10 potato
, I would like it to look like this:
pig acorn 30
pig carrot 10
pig potato 10
First of all - this has little to do with CSV itself. If you want to count the values like here, using a dictionary is a good idea, so what you need is something like (i assume that animals and foods are lists):
After this loop you will have a dictionary with keys that are (animal, food) tuples and values that are the counts. So you can write them to csv like: