如何在pandas中打印特定列的内容

2024-09-29 23:22:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含2列的excel文件(第1列=单词,第2列=线索)。我要做的是使用熊猫,随机选择一个工作表'字'列,打印它的线索(从第2列)和创建一个刽子手游戏。 如果不打印线索部分,我下面的代码可以正常工作,但我无法完成的是打印随机选择的单词对应的线索。你知道怎么做吗??在

import random
import pandas as ps
df1=ps.read_excel("C:/Python27/hangman_clues.xlsx")
#Randomly select a word from the 'Word' Column and convert to lowercase
word=random.choice(df1["Word"]).lower()
print "Welcome to Hangman"
print "Your Clue is"
#This is where I want to print the clue from 2nd column based on the 
randomly selected word which I am unable to accomplish. Tried 
df2=df1.set_index("Word",drop=False) but did not help much.

#below code works fine
guessedword=list('_'*len(word))
ctr=0
while ctr<len(word)+5:
    guessedchar=raw_input("Guess a char:")
    if guessedchar in word:
           getindex=[i.start() for i in re.finditer(guessedchar,word)]
           for index in getindex:
              guessedword[index]=guessedchar
              getindex=[]
              guessword="".join(guessedword)
           print str(guessedword)
           if word==guessword:
               print "you win"
               break


    ctr=ctr+1

Tags: thetoinindex单词excelworddf1
2条回答

您可以使用df1.sample(n=1),它将返回一个随机选择行的数据帧。在

df_random_obs = df1.sample(n=1)
word = df_random_obs['Word']
clue = df_random_obs['Clue']

你可以得到一个随机索引,并将其用于单词和相应的线索。在

index = random.randint(0, len(df1["Word"]))
word = df1["Word"][index]
print("Your clue is {}".format(df1["Clue"][index]))

相关问题 更多 >

    热门问题