당신은 하나를 사용하고 na.replace
수 있습니다
df = spark.createDataFrame([
('Tablet',), ('Phone',), ('PC',), ('Other',), (None,)
], ["device_type"])
df.na.replace(deviceDict, 1).show()
+-----------+
|device_type|
+-----------+
| Mobile|
| Mobile|
| Desktop|
| Other|
| null|
+-----------+
또는 문자지도 :
from itertools import chain
from pyspark.sql.functions import create_map, lit
mapping = create_map([lit(x) for x in chain(*deviceDict.items())])
df.select(mapping[df['device_type']].alias('device_type'))
+-----------+
|device_type|
+-----------+
| Mobile|
| Mobile|
| Desktop|
| null|
| null|
+-----------+
후자 솔루션 NULL
에 매핑에없는 값을 변환합니다 있습니다 . 이 원하는 행동을하지 않으면 당신은 coalesce
을 추가 할 수 있습니다
from pyspark.sql.functions import coalesce
df.select(
coalesce(mapping[df['device_type']], df['device_type']).alias('device_type')
)
+-----------+
|device_type|
+-----------+
| Mobile|
| Mobile|
| Desktop|
| Other|
| null|
+-----------+