[英]How to get datatype of column in spark dataframe dynamically
I have a dataframe - converted dtypes to map. 我有一个数据框-将dtypes转换为map。
val dfTypesMap:Map[String,String]] = df.dtypes.toMap
Output: 输出:
(PRODUCT_ID,StringType)
(PRODUCT_ID_BSTP_MAP,MapType(StringType,IntegerType,false))
(PRODUCT_ID_CAT_MAP,MapType(StringType,StringType,true))
(PRODUCT_ID_FETR_MAP_END_FR,ArrayType(StringType,true))
When I use type [String] hardcoding in row.getAS[String]
, there is no compilation error. 当我在
row.getAS[String]
使用类型[String]硬编码时,没有编译错误。
df.foreach(row => {
val prdValue = row.getAs[String]("PRODUCT_ID")
})
I want to iterate above map dfTypesMap
and get corresponding value type. 我想遍历地图
dfTypesMap
并获取相应的值类型。 Is there any way to convert dt column types to general types like below? 有什么方法可以将dt列类型转换为如下通用类型?
StringType --> String
MapType(StringType,IntegerType,false) ---> Map[String,Int]
MapType(StringType,StringType,true) ---> Map[String,String]
ArrayType(StringType,true) ---> List[String]
As mentioned, Datasets make it easier to work with types. 如前所述,数据集使使用类型更加容易。 Dataset is basically a collection of strongly-typed JVM objects.
数据集基本上是强类型JVM对象的集合。
You can map your data to case classes like so 您可以像这样将数据映射到案例类
case class Foo(PRODUCT_ID: String, PRODUCT_NAME: String)
val ds: Dataset[Foo] = df.as[Foo]
Then you can safely operate on your typed objects. 然后,您可以安全地对键入的对象进行操作。 In your case you could do
在你的情况下你可以做
ds.foreach(foo => {
val prdValue = foo.PRODUCT_ID
})
For more on Datasets, check out https://spark.apache.org/docs/latest/sql-programming-guide.html#creating-datasets 有关数据集的更多信息,请查看https://spark.apache.org/docs/latest/sql-programming-guide.html#creating-datasets
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.