3

I have a DataFrame named score_df having one column named Score and there are names of indices as following

           Score
year       0.029827
yesterday  0.029827
you        0.089482
zeros      0.029827
zones      0.029827

I have another df having a column named df['keywords'] having various keywords. I need to iterate over this column and search in indices of score_df and if index matches with keyword I need to append it's Score value in a list. I am using following code.

for key_w in df['keyword'].to_list():
    result = score_df.loc[key_w, :]

But it is giving KeyError: 'keyword value'. Can some help me how can I select required value? Thank you

1
  • error is for print ( df['keyword']) ? Commented Jan 19, 2021 at 7:09

2 Answers 2

2

I think you need DataFrame.merge with default inner join:

print (score_df)
              Score
year       0.029827
yesterday  0.029827
you        0.089482
zeros      0.029827
zones      0.029827

print (df)
     keyword
0      aaaaa
1  yesterday
2        you

print (score_df.merge(df, left_index=True, right_on='keyword'))
      Score    keyword
1  0.029827  yesterday
2  0.089482        you

L = score_df.merge(df, left_index=True, right_on='keyword')['Score'].tolist()
print (L)
[0.029827, 0.089482]

Or select index by column keyword in Index.isin and boolean indexing:

L = score_df.loc[score_df.index.isin(df['keyword']), 'Score'].tolist()
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the method filter. For example:

df1

   col
A    0
B    1
C    2

df2

  keys
0    A
1    B
2    Z


df1.filter(df2['keys'], axis=0)

Output:

   col
A    0
B    1

To convert it to list use tolist()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.