Have you tried:
from pyspark.sql import functions as F
df.withColumn('device_id', F.when(col('device')=='desktop', 1).when(col('device')=='mobile', 2).otherwise(None))
Note that when chaining when
functions you do not need to wrap the successive calls in an otherwise
function.