I have a pyspark.sql.dataframe.DataFrame object df which contains Continent and Country code.
I also have a dictionary of dictionary dicts which contains the lookup value for each column.
import pyspark.sql.functions as F
import pyspark.sql.types as T
df = sc.parallelize([('A1','JP'),('A1','CH'),('A2','CA'),
('A2','US')]).toDF(['Continent','Country'])
dicts = sc.broadcast(dict([('Country', dict([
('US', 'USA'),
('JP', 'Japan'),
('CA', 'Canada'),
('CH', 'China')
])),
('Continent', dict([
('A1','Asia'),
('A2','America')])
)
]))
+---------+-------+
|Continent|Country|
+---------+-------+
| A1| JP|
| A1| CH|
| A2| CA|
| A2| US|
+---------+-------+
I want to replace both Country and Continent into it lookup value as I have try:
preprocess_request = F.udf(lambda colname, key:
dicts.value[colname].get[key],
T.StringType())
df.withColumn('Continent', preprocess_request('Continent', F.col('Continent')))\
.withColumn('Country', preprocess_request('Country', F.col('Country')))\
.display()
but got me error said object is not subscriptable.
What I expect exactly like this:
+---------+-------+
|Continent|Country|
+---------+-------+
| Asia| Japan|
| Asia| China|
| America| Canada|
| America| USA|
+---------+-------+