반응형
pyspark에서 Dataframe 열을 String 유형에서 Double 유형으로 변경하는 방법
열이 문자열 인 데이터 프레임이 있습니다. PySpark에서 열 유형을 Double 유형으로 변경하고 싶었습니다.
다음은 방법입니다.
toDoublefunc = UserDefinedFunction(lambda x: x,DoubleType())
changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))
로지스틱 회귀 분석을 실행하는 동안 오류가 발생하므로 이것이 문제의 원인인지 궁금합니다.
여기에는 UDF가 필요하지 않습니다. Column
이미 인스턴스 와 함께 cast
메소드 를 제공 합니다 .DataType
from pyspark.sql.types import DoubleType
changedTypedf = joindf.withColumn("label", joindf["show"].cast(DoubleType()))
또는 짧은 문자열 :
changedTypedf = joindf.withColumn("label", joindf["show"].cast("double"))
표준 문자열 이름 (다른 변형도 지원 될 수 있음)이 simpleString
값에 해당 합니다. 따라서 원자 유형의 경우 :
from pyspark.sql import types
for t in ['BinaryType', 'BooleanType', 'ByteType', 'DateType',
'DecimalType', 'DoubleType', 'FloatType', 'IntegerType',
'LongType', 'ShortType', 'StringType', 'TimestampType']:
print(f"{t}: {getattr(types, t)().simpleString()}")
BinaryType: binary
BooleanType: boolean
ByteType: tinyint
DateType: date
DecimalType: decimal(10,0)
DoubleType: double
FloatType: float
IntegerType: int
LongType: bigint
ShortType: smallint
StringType: string
TimestampType: timestamp
예를 들어 복잡한 유형
types.ArrayType(types.IntegerType()).simpleString()
'array<int>'
types.MapType(types.StringType(), types.IntegerType()).simpleString()
'map<string,int>'
열 이름을 유지하고 입력 열과 동일한 이름을 사용하여 추가 열 추가를 방지합니다.
changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))
주어진 대답은 문제를 처리하기에 충분하지만 Spark의 새 버전을 소개 할 수있는 다른 방법을 공유하고 싶습니다 (확실 하지 않습니다 ). 그래서 주어진 대답은 그것을 잡지 못했습니다.
spark 문에서 col("colum_name")
키워드로 열에 도달 할 수 있습니다 .
from pyspark.sql.functions import col , column
changedTypedf = joindf.withColumn("show", col("show").cast("double"))
해결책은 간단했습니다.
toDoublefunc = UserDefinedFunction(lambda x: float(x),DoubleType())
changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))
반응형
'Development Tip' 카테고리의 다른 글
Linq의 여러 WHERE 절 (0) | 2020.10.28 |
---|---|
jar 파일에는 정확히 무엇이 포함됩니까? (0) | 2020.10.28 |
Windows Forms ProgressBar : 선택 윤곽을 시작 / 중지하는 가장 쉬운 방법? (0) | 2020.10.28 |
작은 메모리에서 실행되는 사용 가능한 대화 형 언어는 무엇입니까? (0) | 2020.10.27 |
Google 크롬 확장 프로그램에서 프로그래밍 방식으로 devtools를 열 수 있나요? (0) | 2020.10.27 |