dataframe - pyspark 加入空条件
问题描述
我正在尝试根据“年份”和“发票”列加入两个 pyspark 数据框,如下所示。但是如果df1中缺少“年份”,那么我需要仅基于“发票”加入
df1:
Year invoice Status Item
2020 262 YES bag
2019 252 YES ball
2018 240 YES pen
2017 228 YES ink
2016 216 NO headphone
2015 213 NO bicycle
198 NO ribbon
175 YES phone
df2:
Year invoice
2020 262
2016 216
2014 175
2013 198
2019 252
预期输出:
Year invoice Status Item
2020 262 YES bag
2016 216 NO headphone
2014 175 YES phone
2013 198 NO ribbon
2019 252 YES ball
我可以加入 df1 和 df2 如下(仅基于年份和发票”列。如果 df1 中缺少年份,我需要添加仅基于发票加入两列的逻辑。
df_results = df1.join(df2, on=['Year', 'invoice'], how='left') \
.drop(df2.Year) \
.drop(df2.invoice)
如果 df1 中没有“年份”,请告诉我如何加入,并且数据框应仅基于“发票”加入。谢谢。
解决方案
我没有你的代码来测试这个,但我会尝试在连接操作中添加一个条件:
cond = ((df1.Year == df2.Year) | df1.Year.isNull()) & (df1.invoice == df2.invoice)
df_results = df1.join(df2, on=cond, how='left') \
.drop(df2.Year) \
.drop(df2.invoice)
推荐阅读
- unit-testing - @WebMvcTest 没有类型存储库的限定 bean
- identityserver4 - IdentityServer4 和 Angular5 与 Oidc-Client
- reactjs - 将谷歌令牌存储在本地存储中是否是一种好习惯
- android - 如何创建多个屏幕尺寸?
- java - 如何根据操作更改启动器活动
- javascript - .ini 上的 SMTP 详细信息
- reference - Edge 无法访问简单的弹出参考
- mysql - mysql滚动总和累积序列化
- ios - Swift iOS ReactiveKit:调用观察者导致多次触发动作?
- java - 使用存储在外部文件中的值初始化变量