[英]spark data frame operation row and column level useing scala
原始數據框
0.2 0.3
+------+------------- -+
| name| country |
+------+---------------+
|Raju |UAS |
|Ram |Pak. |
|null |China |
|null |null |
+------+--------------+
I Need this
+------+--------------+
|Nwet|wet Con |
+------+--------------+
|0.2 | 0.3 |
|0.2 | 0.3 |
|0.0 | 0.3. |
|0.0 | 0.0 |
+------+--------------+
我想創建一個 Udf 。 對於兩個列
這將應用於 Name Column 它檢查它是否不為 null 然后它返回 0.2 return 0.0 。 並且相同的 Udf 適用於 country 列檢查它是否為 null 返回 0.0 。 不為空則返回 0.3
使用 apache 的 StringUtils:
val transcodificationName: UserDefinedFunction =
udf { (name: String) => {
if (StringUtils.isBlank(name)) 0.0
else 0.2
}
}
val transcodificationCountry: UserDefinedFunction =
udf { (country: String) => {
if (StringUtils.isBlank(country)) 0.0
else 0.3
}
}
dataframe
.withColumn("Nwet", transcodificationName(col("name"))).cast(DoubleType)
.withColumn("wetCon", transcodificationCountry(col("country"))).cast(DoubleType)
.select("Nwet", "wetcon")
編輯:
val transcodificationColumns: UserDefinedFunction =
udf { (input: String, columnName:String) => {
if (StringUtils.isBlank(country)) 0.0
else if(columnName.equals("name")) 0.2
else if(columnName.equals("country") 0.3
else 0.0
}
}
dataframe
.withColumn("Nwet", transcodificationColumns(col("name"), "name")).cast(DoubleType)
.withColumn("wetCon", transcodificationColumns(col("country")), "country").cast(DoubleType)
.select("Nwet", "wetcon")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.