Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 如何从spark中的字符串列中提取数字部分?_Scala_Apache Spark Sql - Fatal编程技术网

Scala 如何从spark中的字符串列中提取数字部分?

Scala 如何从spark中的字符串列中提取数字部分?,scala,apache-spark-sql,Scala,Apache Spark Sql,我是一个新的火花和尝试玩数据得到实践。我在scala中使用databricks,对于数据集,我使用的是来自kaggle的fifa 19完整球员数据集。名为Weight的列之一,其中包含如下数据 +------+ |Weight| +------+ |136lbs| |156lbs| |136lbs| |... | |... | +------+ 我想把这个列改成这样 +------+ |Weight

我是一个新的火花和尝试玩数据得到实践。我在scala中使用databricks,对于数据集,我使用的是来自kaggle的fifa 19完整球员数据集。名为Weight的列之一,其中包含如下数据

    +------+
    |Weight|
    +------+
    |136lbs|
    |156lbs|
    |136lbs|
    |...   |
    |...   |
    +------+
我想把这个列改成这样

    +------+
    |Weight|
    +------+
    |136   |
    |156   |
    |136   |
    |...   |
    |...   |
    +------+

任何人都可以帮助我如何更改spark sql中的列值。

您可以创建一个新列并使用regexp\u replace

dataFrame.withColumn("Weight2", regexp_replace($"Weight" , lit("lbs"), lit("")))

您可以创建一个新列并使用regexp\u replace

dataFrame.withColumn("Weight2", regexp_replace($"Weight" , lit("lbs"), lit("")))

下面是使用regex和regexp\u extract内置函数的另一种方法:

import org.apache.spark.sql.functions.regexp_extract

val df = Seq(
"136lbs",
"150lbs",
"12lbs",
"30kg",
"500kg")
.toDF("weight")

df.withColumn("weight_num", regexp_extract($"weight", "\\d+", 0))
  .withColumn("weight_unit", regexp_extract($"weight", "[a-z]+", 0))
  .show

//Output
+------+----------+-----------+
|weight|weight_num|weight_unit|
+------+----------+-----------+
|136lbs|       136|        lbs|
|150lbs|       150|        lbs|
| 12lbs|        12|        lbs|
|  30kg|        30|         kg|
| 500kg|       500|         kg|
+------+----------+-----------+

下面是使用regex和regexp\u extract内置函数的另一种方法:

import org.apache.spark.sql.functions.regexp_extract

val df = Seq(
"136lbs",
"150lbs",
"12lbs",
"30kg",
"500kg")
.toDF("weight")

df.withColumn("weight_num", regexp_extract($"weight", "\\d+", 0))
  .withColumn("weight_unit", regexp_extract($"weight", "[a-z]+", 0))
  .show

//Output
+------+----------+-----------+
|weight|weight_num|weight_unit|
+------+----------+-----------+
|136lbs|       136|        lbs|
|150lbs|       150|        lbs|
| 12lbs|        12|        lbs|
|  30kg|        30|         kg|
| 500kg|       500|         kg|
+------+----------+-----------+