[英]Subtracting a particular columns particular content from another column pandas
[英]How to print content of a particular column in pandas
我有2列的excel文件(第1列=單詞,第2列=線索)。 我想做的是使用熊貓,隨機選擇一個工作表“單詞”列,打印它的線索(來自列2)並創建一個a子手游戲。 如果沒有打印線索部分,下面的代碼就可以正常工作,但是我無法完成的是為隨機選擇的單詞打印相應的線索。 任何想法如何做到這一點?
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]))
您可以使用df1.sample(n=1)
,它將返回一個隨機選擇的行的DataFrame。
df_random_obs = df1.sample(n=1)
word = df_random_obs['Word']
clue = df_random_obs['Clue']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.