简体   繁体   English

使用python写入CSV-Datewise列

[英]Writing into CSV using python - Datewise columns

I have to write result of a number of metrics in a CSV file for past 14 days. 我必须在过去14天内将许多指标的结果写入CSV文件。 First column contains name of all metrics and then other columns are 14 subsequent dates. 第一列包含所有指标的名称,然后其他列是14个后续日期。 The result of these metrics are written to the each cell corresponding to that metrics row and date column. 这些指标的结果将写入与该指标行和日期列相对应的每个单元格中。

I did using a python code. 我确实使用了python代码。 For each date I am calculating the metrics and storing in separate variables. 对于每个日期,我都会计算指标并将其存储在单独的变量中。 I am confused on how to write these into the above described CSV format. 我对如何将它们写入上述CSV格式感到困惑。 Which is the right data structure. 哪个是正确的数据结构。 Do I need to have separate list for every metrics or dictionaries can help? 每个指标或词典都需要帮助的我需要单独列出吗?

Code is too long I am just writing the flow - Code - 代码太长,我只是在编写流程-代码-

  for each date:
               result_matrix_1=query(DB1)
               result_matrix_1=query(DB2)
               # Here i am confused with the DS to store these results in to CSV

sample output type - 样本输出类型-

Metric    date1    date2

session   21       34

users     10       16

first you need to create a list like this 首先,您需要创建一个像这样的列表

['name1','date1'],['name2','date2'],......,['name14','date14'] ['name1','date1'],['name2','date2'],......,['name14','date14']

or any other way like 或其他任何方式

['name1','date1','date2','date3','date4','date5'], ['name2','date1','date2','date3','date4','date5'],......,['name14','date1','date2','date3','date4','date5'] ['name1','date1','date2','date3','date4','date5'],['name2','date1','date2','date3','date4','date5' ],......,['name14','date1','date2','date3','date4','date5']

then you write this list into you .csv file using code like this: 然后使用以下代码将此列表写入.csv文件:

a = [['name1','date1'],['name2','date2'],......,['name14','date14']]
import csv

with open("matrix.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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