[英]Pyspark: Get the amount of distinct combinations between two columns
我需要能夠在兩個單獨的列中獲得不同組合的數量。
在這個來自“動物”和“顏色”列的示例中,我想要得到的結果是 3,因為出現了三種不同的列組合。 基本上,Animal 或 Color 在不同的行中可以相同,但如果兩行具有相同的 Animal AND Color,則應從該計數中省略。
Animal | Color
Dog | Brown
Dog | White
Cat | Black
Dog | White
我知道您可以將數據添加到一個集合中,這將消除重復項,但我似乎無法讓它與多個變量一起使用。
這是我試圖解決這個問題的示例代碼。
d = d.rdd
d = d.map(lambda row: (row.day.year, row.number))
print(d.take(2000))
d_maxNum = d.reduceByKey(lambda max_num, this_num: this_num if this_num > max_num else max_num)
print(d_maxNum.collect())
Pyspark 有您可以使用的dropDuplicates
方法參考。
df = sc.parallelize([Row(Animal='Dog', Color='White'), Row(Animal='Dog', Color='Black'), Row(Animal='Dog', Color='White'), Row(Animal='Cat', Color='White')]).toDF()
df.dropDuplicates(['Animal', 'Color']).count()
這將使輸出為 3。
您可以使用distinct
功能。
##Perform distinct on entire dataframe.
df.distinct().show()
##Perform distinct on certain columns of dataframe
df.select('Animal','Color').distinct().show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.