简体   繁体   中英

storing .csv data in Python

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. Eg, 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):

counts = {}
for animal, food in zip(animals, foods):
    counts.setdefault((animal, food), 0)
    counts[(animal, food)] += 1

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:

for ((animal, food), count) in counts.items():
    csv_writer.writerow([animal, food, count])

It looks that you do not know the wonderful Counter class of collections . Here is the documentation .

If you want to count your variable pairs:

c = Counter(zip(var1, var2))

to write the results, use the csv library, as reported in zetciu answer, but remember that Counter instances are dict .

with open('result.csv', 'wb') as csvfile:
    csv_writer = csv.writer(csvfile)
    csv_writer.writerow(["animals", "food", "count"])
    for pair,count in c.items():
         animal, food = pair
         csv_writer.writerow([animal, food, count])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM