网络编程
位置:首页>> 网络编程>> Python编程>> Pandas 同元素多列去重的实例

Pandas 同元素多列去重的实例

作者:迪小子  发布时间:2023-02-09 21:03:32 

标签:Pandas,多列,去重

有一些问题可能会遇到同元素多列去重问题,下面介绍一种非常简单效率也很快的做法,用pandas来实现。

首先我们看一下数据类型:


G1 G2
a b
b a
c d
d c
e f

对这样的两列数据进行同元素去重,最终得到结果为:


G1 G2
a b
c d
e f

代码如下:


#-*- coding: utf-8 -*-
data = {'G1':['a','b','c','d','e'],'G2':['b','a','d','c','f']}
data = pd.DataFrame(data)
data['G3'] = data['G1'] + '|' + data['G2']
p = []
for i in data['G3'].tolist():
 tmp = sorted(i.split('|')) # The most important part,sort
 p.append(tmp[0] + '|' + tmp[1])
data['G3'] = pd.Series(p)
data = data.drop_duplicates('G3')

来源:https://blog.csdn.net/u011476718/article/details/62416776

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com