Search code examples
pythondataframepysparklookup.when

Get value from another static table when "ID_ENTE_COMPETENZA_TIPO" is equal to 'S' in an dataframe


i have a simple dataframe like:

df
    id_ente_competenza_tipo | INOLTRO_PSAP2 
       3                           S    
       3                           S
       3                           N
       2                           S

i have another dataframe static table:

df_ente
id_ente_competenza_tipo| des_ente_competenza_tipo
  1                       Carabinieri
  2                       Polizia di Stato
  3                       Emergenza Sanitaria

i want that if df.ID_ENTE_COMPETENZA_TIPO =='S' --> df.ID_ENTE_COMPETENZA_TIPO =df_ente.des_ente_competenza_tipo where df.id_ente_competenza_tipo ==df_ente.id_ente_competenza_tipo otherwise df.id_ente_competenza_tipo

i want this:

id_ente_competenza_tipo |    INOLTRO_PSAP2 
         Emergenza Sanitaria      S    
         Emergenza Sanitaria      S
         3                        N
         Polizia di Stato         S

my code is this but there is amoreefficient way?

df=df.withColumn("ID_ENTE_COMPETENZA_TIPO",F.when(df.INOLTRO_PSAP2=="S",df_ente.join(df,
df_ente["id_ente_competenza_tipo"]==df["ID_ENTE_COMPETENZA_TIPO"])\
.select("des_ente_competenza_tipo").head()[0]).otherwise(df.ID_ENTE_COMPETENZA_TIPO))

Thanks for help Regards


Solution

  • It's best to apply the logic of choosing between des_ente_competenza_tipo or id_ente_competenza_tipo based on INOLTRO_PSAP2 after joining the tables. Use the when and otherwise you had applied in the code snippet.

    
    from pyspark.sql import functions as F
    
    df = spark.createDataFrame([(3, "S", ),(3, "S", ),(3, "N", ),(2, "S", ),], ("id_ente_competenza_tipo", "INOLTRO_PSAP2"))
    
    df_ente = spark.createDataFrame([(1, "Carabinieri", ),(2, "Polizia di Stato", ),(3, "Emergenza Sanitaria", ),], ("id_ente_competenza_tipo", "des_ente_competenza_tipo"))
    
    
    results = df.join(df_ente, ["id_ente_competenza_tipo"])\
      .withColumn("id_ente_competenza_tipo", F.when(df["INOLTRO_PSAP2"] == "N", df["id_ente_competenza_tipo"]).otherwise(df_ente["des_ente_competenza_tipo"]))\
      .select("id_ente_competenza_tipo", "INOLTRO_PSAP2")
    
    results.show()
    

    Output

    +-----------------------+-------------+
    |id_ente_competenza_tipo|INOLTRO_PSAP2|
    +-----------------------+-------------+
    |       Polizia di Stato|            S|
    |    Emergenza Sanitaria|            S|
    |    Emergenza Sanitaria|            S|
    |                      3|            N|
    +-----------------------+-------------+