use*_*882 4 scala apache-spark apache-spark-sql
大家好我加载了一个csv作为数据帧,我想将所有列转换为浮动,知道该文件是大写所有列名称
val spark = SparkSession.builder.master("local").appName("my-spark-app").getOrCreate()
val df = spark.read.option("header",true).option("inferSchema", "true").csv("C:/Users/mhattabi/Desktop/dataTest2.csv")
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激
以此DataFrame为例:
val df = sqlContext.createDataFrame(Seq(("0", 0),("1", 1),("2", 0))).toDF("id", "c0")
Run Code Online (Sandbox Code Playgroud)
与架构:
StructType(
StructField(id,StringType,true),
StructField(c0,IntegerType,false))
Run Code Online (Sandbox Code Playgroud)
您可以通过.columns函数循环遍历DF列:
val castedDF = df.columns.foldLeft(df)((current, c) => current.withColumn(c, col(c).cast("float")))
Run Code Online (Sandbox Code Playgroud)
所以新的DF架构看起来像:
StructType(
StructField(id,FloatType,true),
StructField(c0,FloatType,false))
Run Code Online (Sandbox Code Playgroud)
编辑:
如果你想从转换中排除某些列,你可以做类似的事情(假设我们想要排除列id):
val exclude = Array("id")
val someCastedDF = (df.columns.toBuffer --= exclude).foldLeft(df)((current, c) =>
current.withColumn(c, col(c).cast("float")))
Run Code Online (Sandbox Code Playgroud)
where exclude是我们要从转换中排除的所有列的数组.
所以这个新DF的架构是:
StructType(
StructField(id,StringType,true),
StructField(c0,FloatType,false))
Run Code Online (Sandbox Code Playgroud)
请注意,这可能不是最好的解决方案,但它可以作为一个起点.
| 归档时间: |
|
| 查看次数: |
3148 次 |
| 最近记录: |