如何比较两个数据帧并标记一个数据帧?

2024-10-02 14:24:13 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有两个数据帧如下所示,并试图得到结果的数据帧如下所示。你知道吗

只想与ID列比较数据帧。你知道吗

id  name    item    price   
1   abc      pen    10  
2   bcd      pencil 10  
3   cde      book   100 
4   def      stick  50  
5   abc      pencil 10  


id  name    item    price   
2   xyz     pen     10  
50  ahjl    phone   1000    
1   fff     mouse   200 
5   ank     stamp   20  
49  anve    cable   2000    

结果表

id  name    item    price   flag
2   xyz      pen    10      yes
5   ank      stamp  20      yes
1   fff      mouse  200     yes
50  ahjl     phone  1000    no
49  anve     cable  2000    no

我可以用python实现这一点。 你能帮我和Pypark一起做这个吗。你知道吗

谢谢你

安库什·雷迪


Tags: 数据nameidfffphoneitempriceyes
1条回答
网友
1楼 · 发布于 2024-10-02 14:24:13

假设您的数据帧分别称为df1df2

import pyspark.sql.functions as F

df2.join(
    df1.selectExpr("id", "'yes' as flag").dropDuplicates(), 
    ["id"], "left"
).withColumn("flag", F.coalesce(F.col("flag"), F.lit("no"))).show()

+ -+  -+  +  -+  +
| id| item|name|price|flag|
+ -+  -+  +  -+  +
| 50|phone|ahjl| 1000|  no|
|  5|stamp| ank|   20| yes|
|  1|mouse| fff|  200| yes|
| 49|cable|anve| 2000|  no|
|  2|  pen| xyz|   10| yes|
+ -+  -+  +  -+  +

详情:

  • 用常量yesdf1预填充flag
  • df2连接,将flag列中的null替换为no

相关问题 更多 >