python hlookup查找功能

时间:2018-11-29 10:27:24

标签: python pandas dataframe

我有两个这样的数据帧,我想将df2的信息与df1合并

df1

Topic1  Topic2  Topic3  
Aa        Bb      Cc  
Dd        Ee      Ff  
Gg        Hh      Ii

df2

My_topics    
Topic2
Topic3
Topic1

所需的输出是

My_topics   Word1  Word2  Word3 
Topic2      Bb      Ee    Hh
Topic3      Cc      Ff    Ii
Topic1      Aa      Dd    Gg

我使用了lookup函数,但无法获得所需的输出。

df2['Word1'] = df1.set_index('I dont know what put here').lookup(df2['My_topics'],df2['My_topics'])

1 个答案:

答案 0 :(得分:1)

给予

>>> df1
  Topic1 Topic2 Topic3
0     Aa     Bb     Cc
1     Dd     Ee     Ff
2     Gg     Hh     Ii
>>> 
>>> df2
  My_topics
0    Topic2
1    Topic3
2    Topic1

您可以发布

>>> df3 = pd.concat([df2, df1.reindex(columns=df2['My_topics']).T.reset_index(drop=True)], axis=1)
>>> new_names = {i:'Word{}'.format(i + 1) for i in range(len(df1.columns))}
>>> df3.rename(columns=new_names, inplace=True)
>>> 
>>> df3
  My_topics Word1 Word2 Word3
0    Topic2    Bb    Ee    Hh
1    Topic3    Cc    Ff    Ii
2    Topic1    Aa    Dd    Gg