1

저는 PySpark의 초보자입니다.Pyspark : 사전 검색으로 열의 값 바꾸기

'device_type'열이있는 DataFramedf의 스파크가 있습니다.

"Tablet"또는 "Phone"에있는 모든 값을 "Phone"으로 바꾸고 "PC"를 "Desktop"으로 바꿉니다.

다음과 같은 처리를 할 수 있습니다 파이썬에서

,

deviceDict = {'Tablet':'Mobile','Phone':'Mobile','PC':'Desktop'} 
df['device_type'] = df['device_type'].replace(deviceDict,inplace=False) 
I이 사용 PySpark을 달성 할 수있는 방법

? 감사!

답변

0

당신은 하나를 사용하고 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| 
+-----------+