首页 > 解决方案 > 如何在熊猫中打印特定列的内容

问题描述

我有一个包含 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

标签: pythonpandas

解决方案


您可以获得一个随机索引并将其用于单词和相应的线索。

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

推荐阅读