我想用 Spark SQL 和 DataFrame 復制 Pandas nunique 函式。我有以下幾點:
%spark
import org.apache.spark.sql.functions.countDistinct
import org.apache.spark.sql.functions._
val df = spark.read
.format("csv")
.option("delimiter", ";")
.option("header", "true") //first line in file has headers
.load("target/youtube_videos.csv")
println("Distinct Count: " df.distinct().count())
val df2 = df.select(countDistinct("likes"))
df2.show(false)
這可以作業并列印喜歡列的唯一計數,如下所示:
Distinct Count: 109847
---------------------
|count(DISTINCT likes)|
---------------------
|27494 |
---------------------
如何在一個 SQL 中執行此操作,以便獲得所有單個列的摘要?
uj5u.com熱心網友回復:
您可以輕松地迭代 DataFrame 中的所有列并收集結果,否則您也可以將其轉換為 DataFrame
import pyspark.sql.functions as F
data = {"col1" : [np.random.randint(10) for x in range(1,10)],
"col2" : [np.random.randint(100) for x in range(1,10)]}
mypd = pd.DataFrame(data)
sparkDF = sql.createDataFrame(mypd)
sparkDF.show()
---- ----
|col1|col2|
---- ----
| 4| 54|
| 2| 90|
| 4| 70|
| 4| 37|
| 7| 63|
| 8| 59|
| 0| 52|
| 2| 76|
| 7| 79|
---- ----
迭代 DataFrame 列
sparkDF.select([F.countDistinct(F.col(c)).alias(c) for c in sparkDF.columns]).show()
---- ----
|col1|col2|
---- ----
| 5| 9|
---- ----
uj5u.com熱心網友回復:
我能夠得到我想要的結果,如下所示:
import org.apache.spark.sql.functions.countDistinct
import org.apache.spark.sql.functions.col
// Print the unique values for each column
df.select(df.columns.map(c => countDistinct(col(c)).alias(c)): _*).show(false)
上面的代碼片段列印:
------------- ---------- ----------- -------- ----------------- ----- ----- -------- -------- -------- -------------------- -------------------- --------------
|channel_title|channel_id|video_title|video_id|video_upload_date|views|likes|dislikes|comments|age_days|likes_dislikes_ratio|comments_views_ratio|mean_views_day|
------------- ---------- ----------- -------- ----------------- ----- ----- -------- -------- -------- -------------------- -------------------- --------------
|127 |127 |108980 |109846 |109692 |86107|27494|5457 |7104 |5195 |69021 |100809 |109714 |
------------- ---------- ----------- -------- ----------------- ----- ----- -------- -------- -------- -------------------- -------------------- --------------
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/350179.html
