有两个数据框,一个是信息表,另一个是引用表。我需要根据条件乘以两列,下面是详细信息:
Dataframe (信息)
+-----+-----+
| key|value|
+-----+-----+
| a| 10|
| b| 20|
| c| 50|
| d| 40|
+-----+-----+
Dataframe (参考)
+-----+----------+
| key|percentage|
+-----+----------+
| a| 0.1|
| b| 0.5|
+-----+----------+
Dataframe(这是我想要的输出)
+-----+------+
| key|result|
+-----+------+
| a| 1| (10 * 0.1 = 1)
| b| 10| (20 * 0.5 = 10)
| c| 50| (because there are no key matching in reference table, then remain the same)
| d| 40| (because there are no key matching in reference table, then remain the same)
+-----+------+
我已经尝试了下面的代码,但失败了.
df_cal = (
info
.withColumn('result', f.when(f.col('key')==reference.withColumn(f.col('key')), \
f.col('value)*reference.withColumn(f.col('percentage')) ))
.select('key', 'result')
)
df_cal.show()
3条答案
按热度按时间voase2hg1#
连接和相乘。代码和逻辑如下
dba5bblo2#
在总体逻辑保持相同的情况下,与WWNDE的解决方案的细微差别在于使用
coalesce
而不是fillna
。如果在没有子集的情况下使用fillna
,则fillna
也可以填充不想要的列,并且在任何情况下,它在Spark规划中生成新的投影。使用
coalesce
的示例3qpi33ja3#
如果你愿意使用Spark SQL而不是DataFrame API,你可以这样做:
创建 Dataframe 。(可选,因为您已经有数据)
接下来,我们需要创建2个 Dataframe 的视图以运行SQL查询。下面,我们将从
info_df
创建一个名为info
的视图,并从reference_df
创建一个名为reference
的视图最后,我们编写一个查询来执行乘法。该查询在info和reference之间执行左连接,然后将
value
乘以percentage
。关键部分是我们将coalesce
percentage
乘以1。因此,如果percentage
为null,则value
乘以1。输出: