import csv import pandas as pd import random with open('data.csv','a',encoding='utf-8') as csvfile: fieldnames = ['产品','1','2','3','4','5','6','7','8','9','10','11','12'] writer=csv.DictWriter(csvfile,fieldnames=fieldnames) good=["毛巾","香皂","洗发水","护发素","口杯","梳子","水桶","洗衣粉","牙刷","口罩"] for x in range(0,10): product=good[x] a=random.randint(10,70) b=random.randint(10,70) c=random.randint(10,70) d=random.randint(10,70) e=random.randint(10,70) f=random.randint(10,70) g=random.randint(10,70) h=random.randint(10,70) i=random.randint(10,70) j=random.randint(10,70) k=random.randint(10,70) l=random.randint(10,70) data=[{'产品':product,'1':a,'2':b,'3':c,'4':d,'5':e,'6':f,'7':g,'8':h,'9':i,'10':j,'11':k,'12':l}] with open('data.csv', 'w', newline='') as csvfile: for row in data: csvwriter = csv.writer(csvfile) csvwriter.writerow(row) df=pd.DataFrame(data) df.to_csv('data.csv',index=False) print(df)
时间: 2023-12-27 11:03:18 浏览: 85
CSV数据-Pandas-Tests-IO-Data-CSV-Tips-2024-01-09.zip
这段代码是用来生成随机数据,并将数据写入到一个CSV文件中,然后用Pandas将数据读取出来,并打印出来。具体来说,代码中首先定义了需要生成的产品名称和各个月份的销售量字段名,然后使用随机函数生成每个产品在每个月份的销售量,将数据写入到CSV文件中。接着使用Pandas将数据读取出来,并将数据打印出来。需要注意的是,该代码中写入CSV文件的方式是采用追加的方式打开文件,因此如果多次执行该代码,将会在同一个CSV文件中追加新的数据。
阅读全文