python - 在 PySpark 中加入查找表
问题描述
我有 2 个表:表“A”和表“查找”
表 A:
ID Day
A 1
B 1
C 2
D 4
查找表具有每个 ID-Day 组合的百分比值。
表查找:
ID 1 2 3 4
A 20 10 50 30
B 0 50 0 50
C 50 10 10 30
D 10 25 25 40
我的预期输出是在表“A”中有一个名为“百分比”的附加字段,其值是从查找表中填写的:
ID Day Percent
A 1 20
B 1 0
C 2 10
D 4 40
由于两个表都很大,我不想旋转任何表。
解决方案
(在我发布问题后的第二天发布我的答案)
我能够通过将表转换为 pandas 数据框来解决这个问题。
from pyspark.sql.types import *
schema = StructType([StructField("id", StringType())\
,StructField("day", StringType())\
,StructField("1", IntegerType())\
,StructField("2", IntegerType())\
,StructField("3", IntegerType())\
,StructField("4", IntegerType())])
# Day field is String type
data = [['A', 1, 20, 10, 50, 30], ['B', 1, 0, 50, 0, 50], ['C', 2, 50, 10, 10, 30], ['D', 4, 10, 25, 25, 40]]
df = spark.createDataFrame(data,schema=schema)
df.show()
# After joining the 2 tables on "id", the tables would look like this:
+---+---+---+---+---+---+
| id|day| 1| 2| 3| 4|
+---+---+---+---+---+---+
| A| 1| 20| 10| 50| 30|
| B| 1| 0| 50| 0| 50|
| C| 2| 50| 10| 10| 30|
| D| 4| 10| 25| 25| 40|
+---+---+---+---+---+---+
# Converting to a pandas dataframe
pandas_df = df.toPandas()
id day 1 2 3 4
A 1 20 10 50 30
B 1 0 50 0 50
C 2 50 10 10 30
D 4 10 25 25 40
# UDF:
def udf(x):
return x[x['day']]
pandas_df['percent'] = pandas_df.apply(udf, axis=1)
# Converting back to a Spark DF:
spark_df = sqlContext.createDataFrame(pandas_df)
+---+---+---+---+---+---+---+
| id|day| 1| 2| 3| 4|new|
+---+---+---+---+---+---+---+
| A| 1| 20| 10| 50| 30| 20|
| B| 1| 0| 50| 0| 50| 0|
| C| 2| 50| 10| 10| 30| 10|
| D| 4| 10| 25| 25| 40| 40|
+---+---+---+---+---+---+---+
spark_df.select("id", "day", "percent").show()
+---+---+-------+
| id|day|percent|
+---+---+-------+
| A| 1| 20|
| B| 1| 0|
| C| 2| 10|
| D| 4| 40|
+---+---+-------+
如果有人在没有 pandas-df 转换的情况下在 PySpark 中发布答案,我将不胜感激。
推荐阅读
- javascript - 无法同步 mongoose 操作以返回数组
- javascript - .click() 只触发一次然后不再触发,除非我刷新整个页面并且如果我调用 $(document).ready() 则根本不呈现
- python - 熊猫聚合分组与另一列的最大值?
- python - 得到一个字母拆分
- arduino - SPI Micro SD 卡 - 打开文本文件时出错 - 为什么它不起作用?
- javascript - 排序表表单视图 One2many 归档后,JQuery .prepend() 不起作用
- linux - GLFW 链接,未定义对 init 的引用
- azure-ad-b2c - 无法从 Azure AD B2C 获取配置
- php - 查询 MorphToMany 关系 Laravel
- webpack - Babel + Webpack 向 ie11 发送箭头函数