【问题标题】:How to remove column duplication in PySpark DataFrame without declare column name如何在不声明列名的情况下删除 PySpark DataFrame 中的列重复
【发布时间】:2021-11-21 23:06:21
【问题描述】:

这是我在 pandas 中所做的

df = df.loc[:,~df.columns.duplicated()]

如何在 PySpark 中做到这一点?

找到this,但是代码量相差太大

【问题讨论】:

    标签: pandas dataframe pyspark


    【解决方案1】:

    您可能必须手动选择所需的列,或者您必须使用新列。这是因为 spark 数据帧是不可变的。

    【讨论】:

    • 你能给出带有模拟数据框的示例代码吗?
    • 我假设您有两个具有相同数据的不同列。我的理解正确吗?
    【解决方案2】:

    您需要使列名唯一,然后创建一个具有唯一列的新数据框:

    df=spark.createDataFrame([[1,2,3,4,5,6]], schema=["A","B","B","C","C","C"])
    #+---+---+---+---+---+---+
    #|  A|  B|  B|  C|  C|  C|
    #+---+---+---+---+---+---+
    #|  1|  2|  3|  4|  5|  6|
    #+---+---+---+---+---+---+
    
    result=list()
    for c in df.columns:
        while c in result:
            c = c + "_" 
        result.append(c)
    #result = ['A', 'B', 'B_', 'C', 'C_', 'C__']
    
    df_unique=spark.createDataFrame(df.rdd, result) \
        .select(*set(df.columns))
    #+---+---+---+
    #|  A|  C|  B|
    #+---+---+---+
    #|  1|  4|  2|
    #+---+---+---+
    

    【讨论】:

      【解决方案3】:

      遇到类似问题,我一直在使用以下函数删除数据框中的重复列并返回一个新列。

      请注意,此函数会保留重复列的第一次出现:

      def drop_dup_cols(df: DataFrame) -> DataFrame:
          """
          The function returns a DataFrame with unique columns, keeping first occurence 
          :param df: a Spark DataFrame with the duplicated columns
          :returns: a Spark DataFrame, with unique columns
          """
          # Create empty lists to insert duplicated or unique columns   
          newcols = []
          dupcols = []
      
          # Loop through the columns of the DF and append the lists above
          [newcols.append(df.columns[i]) if df.columns[i] not in newcols else dupcols.append(df.columns[i]) for i in range(len(df.columns))]
          
          # Update your DF
          df = df.toDF(*[str(i) for i in range(len(df.columns))])
          for dupcol in dupcols:
              df = df.drop(str(dupcol))
      
          return df.toDF(*newcols)
      

      它接受 DF 并返回相同的内容,但不包含重复的列。

      • 演示(使用@werner 示例 DF):
      df=spark.createDataFrame([[1,2,3,4,5,6]], schema=["A","B","B","C","C","C"])
      
      >>> df.show()
      +---+---+---+---+---+---+
      |  A|  B|  B|  C|  C|  C|
      +---+---+---+---+---+---+
      |  1|  2|  3|  4|  5|  6|
      +---+---+---+---+---+---+
      
      >>> drop_dup_cols(df).show()
      +---+---+---+
      |  A|  B|  C|
      +---+---+---+
      |  1|  2|  4|
      +---+---+---+
      
      

      【讨论】:

        猜你喜欢
        • 2015-01-13
        • 1970-01-01
        • 2014-09-01
        • 2017-04-22
        • 2014-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-09
        相关资源
        最近更新 更多