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
解决方案
您可以获得一个随机索引并将其用于单词和相应的线索。
index = random.randint(0, len(df1["Word"]))
word = df1["Word"][index]
print("Your clue is {}".format(df1["Clue"][index]))
推荐阅读
- php - 哪种是显示图像的最优化方式?
- debugging - 如何在 Atmel Studio 中调试从 FLASH 复制到 RAM 的代码?
- c# - 验证电子邮件地址,但未找到任何行 [位置 0 处没有行。' 错误]
- pytorch - 训练步骤未在 pytorch 闪电中执行
- c# - Unity 3d C#在死亡时停止玩家移动(跌倒)
- github - 我可以将多个 GitHub 存储库组合在一起进行权限管理吗?
- java - 为什么没有办法在java中引用二维数组中的单列?
- c# - 回退策略日志授权事件
- ajax - POST 400 Bad Request 即使那里有数据(Django Rest Framework)
- ios - Flutter 应用程序未在 ios 上运行(来自 CocoaPods 的错误输出)