我有一个包含多列的org.apache.spark.sql.DataFrame.我想使用MinMax Normalization或任何技术缩放1列(lat_long_dist)以在-1和1之间缩放数据,并将数据类型保留为org.apache.spark.sql.DataFrame
scala> val df = sqlContext.csvFile("tenop.csv")
df: org.apache.spark.sql.DataFrame = [gst_id_matched: string,
ip_crowding: string, lat_long_dist: double, stream_name_1: string]
Run Code Online (Sandbox Code Playgroud)
我找到了StandardScaler选项,但是在我可以进行转换之前需要转换数据集.这是一种简单的干净方式.
请记住我是斯卡拉的新手.
这是我想要遵循的示例:https: //spark.apache.org/docs/1.5.1/ml-ann.html
它使用此数据集:https: //github.com/apache/spark/blob/master/data/mllib/sample_multiclass_classification_data.txt
我已经使用下面的代码准备了我的.csv来获取Scala中的分类数据框.
//imports for ML
import org.apache.spark.ml.classification.MultilayerPerceptronClassifier
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator
import org.apache.spark.mllib.util.MLUtils
import org.apache.spark.sql.Row
//imports for transformation
import sqlContext.implicits._
import com.databricks.spark.csv._
import org.apache.spark.mllib.linalg.{Vector, Vectors}
//load data
val data2 = sqlContext.csvFile("/Users/administrator/Downloads/ds_15k_10-2.csv")
//Rename any one column to features
//val df2 = data.withColumnRenamed("ip_crowding", "features")
val DF2 = data2.select("gst_id_matched","ip_crowding","lat_long_dist");
scala> DF2.take(2)
res6: Array[org.apache.spark.sql.Row] = Array([0,0,0], [0,0,1628859.542])
//define doublelfunc
val toDouble = udf[Double, String]( _.toDouble)
//Convert all to double
val featureDf = DF2
.withColumn("gst_id_matched",toDouble(DF2("gst_id_matched")))
.withColumn("ip_crowding",toDouble(DF2("ip_crowding")))
.withColumn("lat_long_dist",toDouble(DF2("lat_long_dist")))
.select("gst_id_matched","ip_crowding","lat_long_dist")
//Define …Run Code Online (Sandbox Code Playgroud) 我有一个数据框,其中每列都是类型因子并且有超过 3000 个级别。有没有办法可以用数值替换每个级别。考虑内置数据框 InsectSprays
> str(InsectSprays)
'data.frame': 72 obs. of 2 variables:
$ count: num 10 7 20 14 14 12 10 23 17 20 ...
$ spray: Factor w/ 6 levels "A","B","C","D",..: 1 1 1 1 1 1 1 1 1 1 ...
Run Code Online (Sandbox Code Playgroud)
更换应如下:
A=1,B=2,C=3,D=4,E=5,F=6。
如果有 3000 个级别:
“美国”=1,“英国”=2....,法国=“3000”。
该解决方案应自动检测级别(例如:3000),然后替换从 1 到 3000 的每个级别。