Othman
Othman

Reputation: 89

iterating rows in Pandas to match values in columns

I build a dictionary app, where I use a 3 column df1 DataFrame (English - German - Spanish). I need to iterate every column where a user given a value in English, and he should post the equivalent word in Spanish and German.

I started the code like that:

for w in df1.index:
  e = df1.loc[w]['English']
  print("Translate: " + e + "in German")
  d = input('')
  print("Now try Spanish\n")
  s = input('')

How to iterate RANDOMLY to check if the supplied input matches the values in a particular row?

Update: Data Sample

| Deutsch            | Englisch        | Español        |
|--------------------|-----------------|----------------|
| bei meinen eltern  | with my paernts | con mis padres |
| zu Hause           | at home         | en casa        |
| stammen aus        | come from       | viene de       |
| ist in ... geboren | was born in     | nació en       |

Upvotes: 0

Views: 1309

Answers (1)

ividito
ividito

Reputation: 336

If your data set is much larger than the number of rows you actually want to iterate through (which is very possible if you have a full dictionary of words), you can create a randomized sample dataframe by using

df2 = df1.sample(frac = 0.1) # randomized sample, 10% of df1
df2 = df1.sample(frac=1) # randomized copy of all of df1

or

df2 = df1.sample(100) # randomized sample, 10 lines from df1

The first will be relative to the size of your df1, as defined by the fraction used as a parameter, the second will be 100 rows regardless of the size of df1. Both are a randomly selected, randomly ordered sample.

Secondly, you want to iterate over the rows. You're passing each row to the user sequentially and waiting on input. The following code should work just fine.

for idx,row in df2.iterrows(): 
    d = input("Translate: " + row.English + " in German")
    if d==row.German:
        print("Good!") # Or another case for successful translation
    else:
        print("The correct answer was "+row.German) # Or another case for incorrect translation
    s = input("Translate: " + row.English + " in Spanish")
    if s==row.Spanish:
        print("Good!")
    else:
        print("The correct answer was "+row.Spanish)

Upvotes: 1

Related Questions