首页 > 解决方案 > 从大型数据集中删除重复列的函数

问题描述

加入 hdfs 表后尝试删除 pyspark df 中的重复列名?

嗨,我正在尝试将多个数据集与 200+ 列的最终数量结合起来。由于要求和大量列,我无法在加入时选择特定列。有没有办法在加入后删除重复的列。我知道有一种方法可以通过 spark df 的 .join 方法来完成,但我加入的基表不是 spark df,我试图避免在加入之前将它们转换为 spark df。

原始 pyspark 连接查询以创建 Spark DF#

cust_base=sqlc.sql('''
Select distinct *
FROM db.tbl1 as t1
LEFT JOIN db.tbl2 as t2 ON (t1.acct_id=t2.acct_id) 
LEFT JOIN db.tbl3 as t3 ON (t1.cust_id=t3.cust_id)
WHERE t1.acct_subfam_mn IN ('PIA','PIM','IAA')
AND t1.active_acct_ct <> 0
AND t1.efectv_dt = '2018-10-31'
AND (t2.last_change_dt<='2018-10-31' AND (t2.to_dt is null OR t2.to_dt > 
'2018-10-31'))
AND (t3.last_change_dt<='2018-10-31' AND (t3.to_dt is null OR t3.to_dt > 
'2018-10-31'))
''').registerTempTable("df1")

检查 cust_id 的不同计数时出错

 a=sqlc.sql('''
 Select 
 count(distinct a.cust_id) as CT_ID
 From df1
 ''')

AnalysisException: "Reference 'cust_id' is ambiguous, could be: cust_id#7L, 
cust_id#171L.; line 3 pos 15"

This is 'cust_id' field present more than once due to join

我想从结果连接的 df 中删除重复的列。提前致谢

标签: pyspark-sql

解决方案


我可以帮助编写一个函数来查找给定数据框中的重复列。

让我们说下面是具有重复列的数据框:

+------+----------------+----------+------+----------------+----------+
|emp_id|emp_joining_date|emp_salary|emp_id|emp_joining_date|emp_salary|
+------+----------------+----------+------+----------------+----------+
|     3|      2018-12-06|     92000|     3|      2018-12-06|     92000|
+------+----------------+----------+------+----------------+----------+

def finddups(*args):
    import collections
    dupes = []
    for cols in args:
        [dupes.append(item) for item, count in collections.Counter(cols).items() if count > 1]
        return dupes

   >>> duplicatecols = finddups(df.columns)
>>> print duplicatecols
['emp_id', 'emp_joining_date', 'emp_salary']

推荐阅读