在Python中存储.csv数据

2024-06-16 09:23:34 发布

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

我有两个变量animalsfood;如果我打印它们,它们看起来像

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

等等。。。你知道吗

我希望此数据以以下格式存储在新的CSV文件中(但不知道如何执行此操作):

animals   food   count
pig       acorn  15
pig       carrot 7
pig       potato 10
dog       acorn  2
dog       meat   10
dog       potato 1

等等。。。 换言之,我希望animals变量中的观察重复出现的次数与food变量中不同类型的项目重复出现的次数相同,并将聚合分数放入新变量中。例如,如果出现了50次pig,其中30次是acorn,10次是carrot,10次是potato,我希望它是这样的:

pig acorn  30
pig carrot 10
pig potato 10

Tags: 数据food格式次数catpotatoanimalsdog
2条回答

首先-这与CSV本身没有什么关系。如果你想像这里一样计算值,使用字典是个好主意,所以你需要的是这样的东西(我假设动物和食物是列表):

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

在这个循环之后,您将拥有一个字典,其中的键是(动物、食物)元组,值是计数。因此您可以将它们写入csv,如:

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

看起来您不知道Counter类的collections。这是documentation。你知道吗

如果要计算变量对:

c = Counter(zip(var1, var2))

要编写结果,请使用zetciu answer中报告的csv库,但请记住计数器实例是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])

相关问题 更多 >