Skip to content
Advertisement

Fastest way to check pandas dataframe and show other elements in the other columns at the same row

If there is a list of words to check…

word_list = ['word1', 'word2', 'word3']

and a data frame like

Word,Score_a,Score_b,Score_c
word5,10,15,20
word6,40,60,80
word3,40,20,10

What is the fastest way to find the corresponding scores for each word in the given word list?

For example, 40, 20, 10 for 'word3'.

Advertisement

Answer

To elaborate on comments above:

df.set_index('Word') #set Word column as index
df.loc['word5', :] # access row

Output:

 Score_a    10
 Score_b    15
 Score_c    20

If you don’t want to set Word as index, you can also use .iloc:

df.iloc[0, :]

Output:

Word        word5
 Score_a       10
 Score_b       15
 Score_c       20

Note the main difference between the two (other than the fact that you can specify column name with loc) is that locis inclusive of the last term when you specify a range.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement