比较数据帧后返回多列

时间:2017-10-14 00:25:50

标签: python pandas

我有两个数据帧,如下所示。它是用熊猫生成的。

DF1

                    0

0       reallocations
1                four
2              payoff

DF2

word             frequency

whether          1
House            1
Sniderman        1
payoff           6

我的目标是阅读df1[0]并检查它是否存在df2[word]中是否存在,然后按以下格式提供输出。

word             frequency

four             0    
whether          1
House            1
Sniderman        1
reallocations    0
four             0
payoff           6

以下是我尝试过的内容:df1.intersection(df2)。我相信我必须为此分配一个列值。

我尝试了Compare pandas dataframes by multiple columns

的解决方案

我很确定有一件小事不允许我连接所需的结果。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您需要外部加入:

df1.rename(columns={'0': 'word'}).merge(df2, how='outer').fillna(0)
# or df1.rename(columns={0: 'word'}).merge(df2, how='outer').fillna(0) if column names in df1
# is a number

#   word            frequency
#0  reallocations   0.0
#1  four            0.0
#2  payoff          6.0
#3  whether         1.0
#4  House           1.0
#5  Sniderman       1.0
相关问题