2017-08-08 89 views
-1

我有一個數據幀(input_dataframe),其所有列的數據類型爲字符串,我有具有相同input_dataframe列名的另一個數據框(output_dataframe)。我需要基於output_dataframe的數據類型來投射input_dataframe的列。我已經寫了下面的代碼是一樣的:更改數據類型在Pyspark

​​3210

我不能夠解決它的十進制數據類型,如十進制數據類型是一樣的十進制(X,Y)。有沒有辦法爲十進制數據類型轉換值。還有沒有其他有效的方法來實現這個解決方案?

+0

這是工作代碼 –

回答

3

我試過只有兩種數據類型,包括十進制類型。請檢查您的數據幀,

>>> df.printSchema() 
root 
|-- col1: integer (nullable = true) 
|-- col2: decimal(10,0) (nullable = true) 

>>> df1.printSchema() 
root 
|-- col1: string (nullable = true) 
|-- col2: string (nullable = true) 

>>> df_schema = {field.name:field.dataType for field in df.schema.fields} 
>>> dfSchema 
{'col2': DecimalType(10,0), 'col1': IntegerType} 

>>> df1_cols = df1.columns 
>>> df1_cols 
['col1', 'col2'] 

>>> for f in df1_cols: 
     df1 = df1.withColumn(f,df1[f].cast(df_schema[f])) 

>>> df1.printSchema() 
root 
|-- col1: integer (nullable = true) 
|-- col2: decimal(10,0) (nullable = true)