我有一個資料框title和bin:
--------------------- -------------
| Title| bin|
--------------------- -------------
| Forrest Gump (1994)| 3|
| Pulp Fiction (1994)| 2|
| Matrix, The (1999)| 3|
| Toy Story (1995)| 1|
| Fight Club (1999)| 3|
--------------------- -------------
如何bin使用 Pyspark 計算新資料框的每一列?例如:
------------ ------------ ------------
| count(bin1)| count(bin2)| count(bin3)|
------------ ------------ ------------
| 1| 1 | 3|
------------ ------------ ------------
這可能嗎?如果你知道怎么做,有人可以幫我嗎?
uj5u.com熱心網友回復:
分組bin并計數,然后根據需要旋轉列bin并重命名結果資料框的列:
import pyspark.sql.functions as F
df1 = df.groupBy("bin").count().groupBy().pivot("bin").agg(F.first("count"))
df1 = df1.toDF(*[f"count_bin{c}" for c in df1.columns])
df1.show()
# ---------- ---------- ----------
#|count_bin1|count_bin2|count_bin3|
# ---------- ---------- ----------
#| 1| 1| 3|
# ---------- ---------- ----------
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/416376.html
標籤:
上一篇:DatabricksType2/SLCD通過SparkStructuredStreaming更新
下一篇:PandasUDF:AttributeError:“NoneType”物件沒有屬性“_jvm”(在UDF之外編碼作業正常)
