簡體   English   中英

Pyspark數據框獲得列表,其中至少一行符合條件

[英]Pyspark dataframe get a list of columns where at least one row meets a condition

我有一個PySpark DataFrame

Col1 Col2 Col3
0.1  0.2  0.3

我想得到列名稱,其中至少有一行符合條件,例如行大於0.1

我的預期結果應該是這種情況:

[Co2 , Co3]

我無法提供任何代碼,因為我真的不知道如何做到這一點。

count滿足謂詞(內部select )的項目並處理結果:

from pyspark.sql.functions import col, count, when

[c for c, v in df.select([
    count(when(col(c) > 0.1, 1)).alias(c) for c in df.columns
]).first().asDict().items() if v]

一步步:

  • 聚合( DataFrame - > DatFrame ):

     df = sc.parallelize([(0.1, 0.2, 0.3)]).toDF() counts = df.select([ count(when(col(c) > 0.1, 1)).alias(c) for c in df.columns ]) 
     DataFrame[_1: bigint, _2: bigint, _3: bigint] 
  • collect first Row

     a_row = counts.first() 
     Row(_1=0, _2=1, _3=1) 
  • 轉換為Python dict

     a_dict = a_row.asDict() 
     {'_1': 0, '_2': 1, '_3': 1} 
  • 當價值真實時,迭代它的項目,保持關鍵:

     [c for c, v in a_dict.items() if v] 

    或明確檢查計數:

     [c for c, v in a_dict.items() if v > 0] 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM