spark dataframe 类型转换

本文介绍了一种在Spark中将DataFrame中的字段从一种类型转换到另一种类型的方法,特别是如何将特定字段转换为double类型,这对于进一步的数据处理和分析非常有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

读一张表,对其进行二值化特征转换。可以二值化要求输入类型必须double类型,类型怎么转换呢?

直接利用spark column 就可以进行转换:

 

DataFrame dataset = hive.sql("select age,sex,race from hive_race_sex_bucktizer ");

/**

* 类型转换

*/

dataset = dataset.select(dataset.col("age").cast(DoubleType).as("age"),dataset.col("sex"),dataset.col("race"));

 

是不是很简单。想起之前的类型转换做法,遍历并创建另外一个满足类型要求的RDD,然后根据RDD创建Datafame,好复杂!!!!

 

		JavaRDD<Row> parseDataset =   dataset.toJavaRDD().map(new Function<Row,Row>() {

			@Override
			public Row call(Row row) throws Exception {
				System.out.println(row);
				long age = row.getLong(row.fieldIndex("age"));
				String sex = row.getAs("sex");
				String race =row.getAs("race");
				double raceV  = -1;
				if("white".equalsIgnoreCase(race)){
					raceV = 1;
				} else if("black".equalsIgnoreCase(race)) {
					raceV = 2;
				} else if("yellow".equalsIgnoreCase(race)) {
					raceV = 3;
				} else if("Asian-Pac-Islander".equalsIgnoreCase(race)) {
					raceV = 4;
				}else if("Amer-Indian-Eskimo".equalsIgnoreCase(race)) {
					raceV = 3;
				}else {
					raceV = 0;
				}
				
				return RowFactory.create(age,("male".equalsIgnoreCase(sex)?1:0),raceV);
			}
		});
		
		StructType schema = new StructType(new StructField[]{
				 createStructField("_age", LongType, false),
				  createStructField("_sex", IntegerType, false),
				  createStructField("_race", DoubleType, false)
				});
		
		DataFrame  df  =  hive.createDataFrame(parseDataset, schema);

  不断探索,不断尝试!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值