所以我试图通过循环一个预先存在的.csv文件来编写一个stroop任务。为此,我将stimuli.csv文件读入数据帧。
.csv文件的组织方式如下:
Colours Congruent Word
0 red 0 blue
1 red 1 red
2 red 0 green
3 blue 1 blue
然后我尝试遍历“颜色”列和“字”列中的数据框检查值。颜色应显示为单词的字体,因此我检查“颜色”列中的索引值以正确显示相应的颜色字体。显示的单词应该是“Word”列中索引的值。我得到了:
Keyerror:0
我看过网上但没有具体的例子可以帮助我。任何人都可以告诉我,如果我这样做错了吗?
import pygame
import sys
import psychopy
import os
import csv
import pandas as pd
pygame.init()
screen = pygame.display.set_mode((1000, 500))
screen.fill((0, 0, 0))
myfont= pygame.font.SysFont("Calibri", 30)
blue= (0,0,255)
green= (0,255,0)
red= (255,0,0)
while 1:
file= r'stimuli.csv'
df= pd.read_csv('%s' %file, delimiter=',', encoding="utf-8-sig")
word= df['Word']
congruent= df['Congruent']
colour= df['Colours']
for index, row in df.iterrows():
word= df[index].iloc['Word']
congruent= df[index].iloc['Congruent']
colour= df[index].iloc['Colours']
if df.iloc[index].iloc['Colours']== 'red':
stim= myfont.render('%s' %word, 1, (255,0,0))
screen.blit(stim, (300,300))
pygame.display.flip()
if df.iloc[index].iloc['Colours']== 'green':
stim= myfont.render('%s' %word, 1, (0,255,0))
screen.blit(stim, (300,300))
pygame.display.flip()
if df.iloc[index].iloc['Colours']== 'blue':
stim= myfont.render('%s' %word, 1, (0,0,255))
screen.blit(stim, (300,300))
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key== pygame.K_ESCAPE:
msg2= myfont.render("Exiting now", 1, (0, 255, 0))
screen.blit(msg2, (300, 300))
pygame.display.flip()
pygame.display.quit()
pygame.quit()
答案 0 :(得分:0)
查看此示例以缩小代码。使用它来更新代码并使事情更具可读性。
df = pd.DataFrame(dict(Colours=['Red','Blue']))
d_colour = dict(Red=(255,0,0),Green=(0,255,0),Blue=(0,0,255))
for index, row in df.iterrows():
colour= df.loc[index,'Colours']
colour_code = d_colour.get(colour)
print(colour_code)
#stim= myfont.render('%s' %word, 1, colour_code)
#screen.blit(stim, (300,300))
#pygame.display.flip()