我是python的新手,我正在编写代码以在一周中的不同天数之间创建性别之间的绘图图,我不知道它有什么问题,因为没有结果,并且有未定义变量的错误'性别”
注意:我正在使用python 3
import calendar
def gender_perday_analysis(filename, gender):
with open(filename, 'r') as f_in:
Reader = csv.DictReader(f_in)
week_days = 0
Female_count = []
Male_count = []
for row in Reader:
if row['gender'] == 'Female':
if row['day_of_week'] == 'Sunday':
week_days+= 1
Female_count.append(week_days)
elif row['day_of_week'] == 'Monday':
week_days+= 1
Female_count.append(week_days)
elif row['day_of_week'] == 'Tuesday':
week_days+= 1
Female_count.append(week_days)
elif row['day_of_week'] == 'Wednesday':
week_days+= 1
Female_count.append(week_days)
elif row['day_of_week'] == 'Thursday':
week_days+= 1
Female_count.append(week_days)
elif row['day_of_week'] == 'Friday':
week_days+= 1
Female_count.append(week_days)
else:
week_days+= 1
Female_count.append(week_days)
else:
week_days+= 1
Male_count.append(week_days)
return Male_count, Female_count
Chicago = './data/Chicago-2016-Summary.csv'
result2 = gender_perday_analysis(Chicago, 'gender')
print(result2)
答案 0 :(得分:1)
if row['gender'] == 'Female':
您传入的是字符串'gender'
,而不是变量gender
。更正以下内容之一:
if row[gender] == 'Female':
答案 1 :(得分:1)
导入csv,可以提供帮助 但添加错误
答案 2 :(得分:0)
可能是您的文件实际上没有读取您认为需要的文件。读取文件可能是错误的。如果可以添加IDE给出的确切错误,将很有帮助。测试读取文件是否有问题。添加此语句
for row in Reader:
print(row)
此外,您可以尝试使用Pandas读取和分析文件,因为这使事情变得更加容易。