【问题标题】:Get list of data types from schema in Apache Spark从 Apache Spark 中的模式获取数据类型列表
【发布时间】:2016-09-17 01:07:54
【问题描述】:

我在 Spark-Python 中有以下代码,可以从 DataFrame 的架构中获取名称列表,效果很好,但是如何获取数据类型列表?

columnNames = df.schema.names

例如,类似:

columnTypes = df.schema.types

有什么方法可以获取 DataFrame 架构中包含的数据类型的单独列表?

【问题讨论】:

    标签: python apache-spark types schema spark-dataframe


    【解决方案1】:

    这里有一个建议:

    df = sqlContext.createDataFrame([('a', 1)])
    
    types = [f.dataType for f in df.schema.fields]
    
    types
    > [StringType, LongType]
    

    参考:

    【讨论】:

    • 或df.printSchema()
    • AttributeError: 'DataFrame' object has no attribute 'printSchema'
    【解决方案2】:

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

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

    这将产生一个org.apache.spark.sql.types.DataType的数组。

    【讨论】:

    • 标签包括python虽然
    • 对于那些碰巧使用 scala 的人来说仍然很有帮助。
    【解决方案3】:

    使用 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      • 1970-01-01
      • 2016-03-27
      • 2017-01-24
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多