我有 2 個包含數百列的 DataFrame。Df1看起來像這樣:
id | col1 | col2 | col3 | .....
1 .2 .3 .3
2 .1 .4 .2
....
Df2看起來像這樣,并且只有 1 行值:
col1 | col2 | col3 | .....
.2 .3 .3
我想將每一行除以Df1by Df2,所以我應該得到這樣的結果:
id | col1 | col2 | col3 | .....
1 .2/.2 .3/.3 .3/.3
2 .1/.2 .4/.3 .2/.3
鑒于我有數百個列,我如何在連接期間不具體指定列名的情況下執行此操作?提前致謝!
uj5u.com熱心網友回復:
我得到了 df2 的值并用 df1 壓縮它。然后遍歷壓縮結構,得到除法值。希望這可以幫助。這是我得到的代碼片段和輸出。
from pyspark.sql.functions import col
df1 = spark.createDataFrame( [('A',2,4),('B',6,8), ('C',10,12) ],['col1','col2','col3'] )
df2 = spark.createDataFrame( [(2,2)],['div1','div2'] )
df1.show()
df2.show()
lr = df2.rdd.take(1)
for c, v in zip(df1.columns[1:], lr[0]):
df1 = df1.withColumn(c, col(c)/v)
df1.show()
---- ---- ----
|col1|col2|col3|
---- ---- ----
| A| 2| 4|
| B| 6| 8|
| C| 10| 12|
---- ---- ----
---- ----
|div1|div2|
---- ----
| 2| 2|
---- ----
---- ---- ----
|col1|col2|col3|
---- ---- ----
| A| 1.0| 2.0|
| B| 3.0| 4.0|
| C| 5.0| 6.0|
---- ---- ----
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/482054.html
標籤:阿帕奇火花 pyspark apache-spark-sql
上一篇:PySpark:呼叫df.foreach方法時出現PicklingError
下一篇:log4net配置使用
