从Apache Spark中的模式获取数据类型列表

问题描述 投票:14回答:3

我在Spark-Python中有以下代码来从DataFrame的模式中获取名称列表,这可以正常工作,但是如何获取数据类型列表?

columnNames = df.schema.names

例如,类似于:

columnTypes = df.schema.types

有没有办法获得DataFrame模式中包含的单独的数据类型列表?

python apache-spark types schema spark-dataframe
3个回答
22
投票

这是一个建议:

df = sqlContext.createDataFrame([('a', 1)])

types = [f.dataType for f in df.schema.fields]

types
> [StringType, LongType]

参考:


5
投票

由于问题标题不是特定于python的,我将在这里添加scala版本:

val tyes = df.schema.fields.map(f => f.dataType)

它将导致一系列org.apache.spark.sql.types.DataType


0
投票

使用schema.dtypes

scala> val df = Seq(("ABC",10,20.4)).toDF("a","b","c")
df: org.apache.spark.sql.DataFrame = [a: string, b: int ... 1 more field]

scala>

scala> df.printSchema
root
 |-- a: string (nullable = true)
 |-- b: integer (nullable = false)
 |-- c: double (nullable = false)

scala> df.dtypes
res2: Array[(String, String)] = Array((a,StringType), (b,IntegerType), (c,DoubleType))

scala> df.dtypes.map(_._2).toSet
res3: scala.collection.immutable.Set[String] = Set(StringType, IntegerType, DoubleType)

scala>
© www.soinside.com 2019 - 2024. All rights reserved.