我从。csv文件中获取记录到Pandas数据框中,然后我想在其中获取随机记录/行,而不使用索引在特定键内,如法语或英语。甚至一个特定的行,如法语单词和它的英文含义,并显示在特定键/行拉出的随机记录。
# this is the .CSV file having French word and English meaning
French,English
partie,part
histoire,history
chercher,search
seulement,only
police,police
pensais,thought
aide,help
demande,request
genre,kind
mois,month
frère,brother
laisser,let
car,because
mettre,to put
Python代码:
data = pandas.read_csv("french_words.csv")
#----converting read .CSV file to dictionary
to_learn = data.to_dict(orient="records")
current_card = random.choice(to_learn)
print(current_card["French"])
#----This is what I want to achieve using dictionary
#----This is what I tried but can't move forward
words_data_dict = {row.French: row.English for (index, row) in data.iterrows()}
我想出了解决办法
# read data from a dataframe into a dictionary
words_data_dict = {row.French: row.English for (index, row) in data.iterrows()}
print(words_data_dict)
# convert the dictionary to a list
list_of_entry = list(words_data_dict.items())
print(list_of_entry)
# generate a random row from the dictionary
random_data = random.choice(list_of_entry)
# specify Key using Index
print(random_data[0])