我有一個 Spark 資料框,如下所示:

另外,另一個資料框:

我期望的輸出如下。我需要有條件地將兩列添加到原始資料資料框中:
“offeramount1”=(數量)的 75%
“offeramount2”=(數量)的 65%
此優惠僅在代碼不在“排除代碼”中時提供

我可以使用 毫無問題地添加列withColumn,但我無法正確比較資料框。
uj5u.com熱心網友回復:
你可以做兩個連接 -'leftanti'和'right':
輸入:
from pyspark.sql import functions as F
df1 = spark.createDataFrame([('c1', 10), ('c2', 12), ('c3', 14), ('c4', 16), ('c5', 18), ('c6', 20), ('c7', 22), ('c8', 24), ('c9', 26), ('c10', 28)], ['codes', 'amount'])
df2 = spark.createDataFrame([('c3',), ('c4',), ('c9',)], ['exclusioncode'])
腳本:
df = (df1
.join(df2, df1.codes == df2.exclusioncode, 'leftanti')
.withColumn('offeramount1', F.round(F.col('amount') * .75, 1))
.withColumn('offeramount2', F.round(F.col('amount') * .65, 1))
.join(df1, ['codes', 'amount'], 'right')
)
df.show()
# ----- ------ ------------ ------------
# |codes|amount|offeramount1|offeramount2|
# ----- ------ ------------ ------------
# | c3| 14| null| null|
# | c1| 10| 7.5| 6.5|
# | c4| 16| null| null|
# | c5| 18| 13.5| 11.7|
# | c2| 12| 9.0| 7.8|
# | c6| 20| 15.0| 13.0|
# | c10| 28| 21.0| 18.2|
# | c8| 24| 18.0| 15.6|
# | c7| 22| 16.5| 14.3|
# | c9| 26| null| null|
# ----- ------ ------------ ------------
您不能用“no offer”填充空值,因為 Spark 中的列僅包含一種資料型別。“no offer” 將是一個字串,而其他值是數字,因此是兩種不同的資料型別。
uj5u.com熱心網友回復:
您可以使用左連接和 when 條件(我將使用每個代碼的金額呼叫amount_df,DataFrame而exclusion_code_df使用DataFrame要排除的代碼):
offer_df = (
amount_df
.join(exclusion_code_df, F.col('codes') == F.col('exclusioncode'), how='left')
.withColumn('offeramount1', F.when(F.col('exclusioncode').isNull(), 0.75 * F.col('amount')).otherwise('no offer'))
.withColumn('offeramount2', F.when(F.col('exclusioncode').isNull(), 0.65 * F.col('amount')).otherwise('no offer'))
.drop('exclusioncode')
)
offer_df如下DataFrame:
----- ------ ------------ ------------------
|codes|amount|offeramount1|offeramount2 |
----- ------ ------------ ------------------
|c1 |10 |7.5 |6.5 |
|c10 |28 |21.0 |18.2 |
|c2 |12 |9.0 |7.800000000000001 |
|c3 |14 |no offer |no offer |
|c4 |16 |no offer |no offer |
|c5 |18 |13.5 |11.700000000000001|
|c6 |20 |15.0 |13.0 |
|c7 |22 |16.5 |14.3 |
|c8 |24 |18.0 |15.600000000000001|
|c9 |26 |no offer |no offer |
----- ------ ------------ ------------------
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/529142.html
