[英]select column value based on index name in Pandas DataFrame
I have a DataFrame named score_df
having one column named Score
and there are names of indices as following我有一个名为 score_df 的
score_df
有一个名为Score
的列,并且索引的名称如下
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.我有另一个
df
有一个名为df['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.我需要遍历此列并在
score_df
的索引中搜索,如果索引与关键字匹配,我需要 append 它是列表中的Score
值。 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'
.但它给出了
KeyError: 'keyword value'
。 Can some help me how can I select required value?有人可以帮助我如何 select 所需的值? Thank you
谢谢
I think you need DataFrame.merge
with default inner join:我认为你需要
DataFrame.merge
与默认内连接:
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
:或 select 在
Index.isin
和boolean indexing
中按列keyword
索引:
L = score_df.loc[score_df.index.isin(df['keyword']), 'Score'].tolist()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.