首页 > 解决方案 > 在 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

由于两个表都很大,我不想旋转任何表。

标签: pythonapache-sparkpysparkapache-spark-sqlpyspark-sql

解决方案


(在我发布问题后的第二天发布我的答案)

我能够通过将表转换为 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 中发布答案,我将不胜感激。


推荐阅读