在两个数据框中显示两列中的唯一元素 [英] Displaying the unique elements from the two columns in two dataframe

查看:73
本文介绍了在两个数据框中显示两列中的唯一元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

data1 = {'date': ['1998', '1999','1999','2000','1999'], 
        'node1': [1,1,2,3,3],
     'node2': [3,4,3,4,8],
     'weight': [1,1,1,1,1], }
df1 = pd.DataFrame(data1, columns = ['date', 'node1','node2','weight'])

data2 = {'date': ['2002','2001','2003','2002','2002','2001'], 
        'node1': [1,1,1,2,2,3],
     'node2': [2,3,4,3,5,4],
     'weight': [1,1,1,1,1,1], }
df2= pd.DataFrame(data2, columns = ['date', 'node1','node2','weight'])

我想搜索两个数据框中的两列(node1,node2),并显示在两个数据框中唯一的节点. 在此示例中,数据1中的8个数据和数据2中的5个数据是数据帧中的唯一节点.

I would like to search through the two columns (node1,node2) in the two dataframes and display the node which are unique in the two dataframes. In this example 8 from data1 and 5 from data2 are the unique nodes in the dataframe.

输出格式:

dataframe1:1999年8月

dataframe1: 8 1999

dataframe2:5 2002

dataframe2: 5 2002

推荐答案

您需要 melt 进行重塑,然后 boolean indexing :

You need melt for reshape and then merge for get unique values, last filter by boolean indexing:

a = df1.drop('weight',1).melt('date', value_name='node').drop('variable',1)
b = df2.drop('weight',1).melt('date', value_name='node').drop('variable',1)

更快捷的选择:

a = pd.DataFrame({'date':np.repeat(df1['date'], 2), 
                  'node':df1[['node1','node2']].values.ravel()})
b = pd.DataFrame({'date':np.repeat(df2['date'], 2), 
                  'node':df2[['node1','node2']].values.ravel()})


c = pd.merge(a, b, how='outer', indicator=True, on='node')

d = c.loc[c['_merge'] == 'left_only', ['date_x', 'node']]
print (d)
   date_x  node
25   1999     8

e = c.loc[c['_merge'] == 'right_only', ['date_y', 'node']]
print (e)
   date_y  node
26   2002     5

详细信息:

print (a)
   date  node
0  1998     1
1  1999     1
2  1999     2
3  2000     3
4  1999     3
5  1998     3
6  1999     4
7  1999     3
8  2000     4
9  1999     8

print (b)
    date  node
0   2002     1
1   2001     1
2   2003     1
3   2002     2
4   2002     2
5   2001     3
6   2002     2
7   2001     3
8   2003     4
9   2002     3
10  2002     5
11  2001     4

这篇关于在两个数据框中显示两列中的唯一元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆