问题:创建一个包含1000行字段/列的文本/csv文件:学生id:唯一标识1:1000得分:40-100之间的随机数日期:最近20天内的任意日期。例如:18/11/2022描述:从你选择的10个单词中随机抽取一个单词种族:随机分配一个种族(如果你不知道意思,谷歌一下)受试者:从10名受试者中随机抽取1名。微积分、统计学、数据库、爱好:从10个爱好中随机选择一个兴趣:从10个兴趣列表中随机选择一个。例如:音乐,非虚构,辩论,游泳,
import csv import random
fields = ['Student Id', 'score', 'date', 'Description',
'Ethinicity', 'Subject', 'Hobby', 'Intrest']
description_list=('Delhi','Noida','goa','varansi','Assam','Kerala','Kolkata','Shilong','Bangluru','Gujrat')
Ethinicity_list=('Sikh','Kashmiri','Rajput','Bhramin','Kayasth','Adiwasi','Odia','Maratha')
Subject_list=('English','Maths','Economics','Hindi','French','Zoology','Chemistry','Physics','Social
Science','Python')
Hobby_list=('Reading','Swimming','Cycling','Biking','Gaming','Sleeping','Teaching','Cricket','Shooting','Talking')
Intrest_list=('Watching
TV','Esports','Football','MotoRacing','Music','Painting','Sketching','Cooking','Cars','Comedy')
data = [
[random.randint(1, 1000),random.randint(40,100),'__',random.choice(description_list),random.choice(Ethinicity_list),random.choice(Subject_list),random.choice(Hobby_list),random.choice(Intrest_list)]
]
filename = "assignment.csv"
with open(filename, 'w') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(data)
生成一行所需的数据。我想用相同的数据生成1000行
您可以将列表推导式与pandas dataframes一起使用,如下所示:
import pandas as pd
# randomly chooses an element of your list/tuple 1000 times
description_choices = [random.choice(description_list) for _ in range(1000)]
...
# create table with random data
df = pd.DataFrame({'Description': description_choices,
...
})
df.to_csv('results.csv')