使用其他两个pyspark Dataframe 作为键值创建pyspark Dataframe 的列

d6kp6zgx  于 2023-01-25  发布在  Spark
关注(0)|答案(1)|浏览(125)

我在pyspark中有以下 Dataframe

Date | Value | Date2
2019/01/10 | 9.5 | null
2019/01/10 | 9.5 | null
2019/01/11 | 4.5 | 2019/01/10
2019/01/12 | 6.7 | 2019/01/11
2019/01/12 | 6.7 | 2019/01/10
2019/01/13 | 9.2 | 2019/01/12
2019/01/14 | 13.6 | 2019/01/13
2019/01/15 | 2.7 | 2019/01/14
2019/01/16 | 7.8 | 2019/01/15

我想创建一个新列,其值是列'Value'的值,但由列Date 2索引(将其作为索引Date)。

Date | Value | Date2 | Value2
2019/01/10 | 9.5 | null | null
2019/01/10 | 9.5 | null | null
2019/01/11 | 4.5 | 2019/01/10 | 9.5
2019/01/12 | 6.7 | 2019/01/11 | 4.5
2019/01/12 | 6.7 | 2019/01/10 | 9.5
2019/01/13 | 9.2 | 2019/01/12 | 6.7
2019/01/14 | 13.6 | 2019/01/13 | 9.2
2019/01/15 | 2.7 | 2019/01/14 | 13.6
2019/01/16 | 7.8 | 2019/01/15 | 2.7

是否存在不涉及join的解决方案?

nzrxty8p

nzrxty8p1#

如果不是一个大的df、susbset,则重命名列并连接。

df.join(df.select('Date','Value').toDF('Date2', 'Value2'), how='left', on='Date2').show()

如果df很大,尝试创建Date和Vlue列的python dict,然后Map到Date2。

from itertools import chain
d = {row['Date']: row['Value']  for row in df.collect()}#Create dict of the columns

m_expr1 = create_map([lit(x) for x in chain(*d.items())])#Mapping expression
#map to date2
df.withColumn("val2", m_expr1[F.col("Date2")]).show()

相关问题