Suppose this is my 1 dataframe with userId, deviceID and Clean_date (date of log in)
df =
| userId | deviceID | Clean_date |
|---|---|---|
| ABC123 | 202030 | 28-Jul-22 |
| XYZ123 | 304050 | 27-Jul-22 |
| ABC123 | 405032 | 28-Jul-22 |
| PQR123 | 385625 | 22-Jun-22 |
| PQR123 | 465728 | 22-Jun-22 |
| XYZ123 | 935452 | 22-Mar-22 |
Suppose following is my dataframe 2 with userId, deviceID and transferdate (date of device transferred to userid)
df2 =
| userId | deviceID | transferdate |
|---|---|---|
| ABC123 | 202030 | 20-May-22 |
| XYZ123 | 304050 | 03-May-22 |
| ABC123 | 405032 | 02-Feb-22 |
| PQR123 | 385625 | 21-Jun-22 |
| PQR123 | 465728 | 2-Jul-22 |
| XYZ123 | 935452 | 26-Apr-22 |
Now, I want to identify 3 scenarios and create new column with identifier
- P1 = User logging in with multiple devices on same day for df 1 and if one of the both devices are not belonging the same user.
- P2 = User logging in with multiple devices on different day for df 1 and if one of the both devices are not belonging the same user.
- NA = User logging in with multiple devices on same day/different day for df 1 and if both devices are belonging the same user.
Hence my output table should look like:
df3 =
| userId | deviceID | Clean_date | transferdate | identifier |
|---|---|---|---|---|
| ABC123 | 202030 | 28-Jul-22 | 20-May-22 | NA |
| XYZ123 | 304050 | 27-Jul-22 | 03-May-22 | P2 |
| ABC123 | 405032 | 28-Jul-22 | 02-Feb-22 | NA |
| PQR123 | 385625 | 22-Jun-22 | 21-Jun-22 | P1 |
| PQR123 | 465728 | 22-Jun-22 | 02-Jul-22 | P1 |
| XYZ123 | 935452 | 22-Mar-22 | 26-Apr-22 | P2 |
I have tried below code:
from pyspark.sql import functions as f, Window
w=Window.partitionBy("userId")
w2 = Window.partitionBy("userId", "Clean_date")
df3 = (
df
.withColumn(
"Priority",
f.when(f.size(f.collect_set("deviceID").over(w2)) > 1, "P1")
.when(f.size(f.collect_set("deviceID").over(w)) > 1, "P2")
.otherwise("NA")
)
)
However, I am unable to incorporate transferdate from df2 in this code.
Any help would be greatly appreciated.