希望在 PySpark 中将字符串列转换为整数列。无法转换的字符串会发生什么情况?



我正在尝试将数据帧中的一列转换为IntegerType。以下是数据帧的示例:

+----+-------+
|From|     To|
+----+-------+
|   1|1664968|
|   2|      3|
|   2| 747213|
|   2|1664968|
|   2|1691047|
|   2|4095634|
+----+-------+

我使用以下代码:

exploded_df = exploded_df.withColumn('From', exploded_df['To'].cast(IntegerType()))

然而,我想知道不是数字的字符串会发生什么,例如,如果我有一个有几个空格的字符串会怎么样?原因是我想过滤数据帧,以便获得在"to"列中没有数字的"From"列的值。

有没有一种更简单的方法可以在不将列转换为IntegerType的情况下通过此条件进行筛选?

谢谢!

无法强制转换的值被设置为null,该列将被视为该类型的nullable列。这里有一个简单的例子:

from pyspark import SQLContext
from pyspark.sql import SparkSession
import pyspark.sql.functions as F
from pyspark.sql.types import IntegerType
spark = SparkSession.builder.getOrCreate()
sql_context = SQLContext(spark.sparkContext)
df = sql_context.createDataFrame([("1",),
("2",),
("3",),
("4",),
("hello world",)], schema=['id'])
print(df.show())
df = df.withColumn("id", F.col("id").astype(IntegerType()))
print(df.show())

输出:

+-----------+
|         id|
+-----------+
|          1|
|          2|
|          3|
|          4|
|hello world|
+-----------+
+----+
|  id|
+----+
|   1|
|   2|
|   3|
|   4|
|null|
+----+

为了验证模式是否正确:

print(df.printSchema())

输出:

None
root
|-- id: integer (nullable = true)

希望这能有所帮助!

我们可以使用regex来检查To列的数据中是否有一些alphabets,spaces,使用spark中的.rlike函数来过滤出匹配的行。

Example:

df=spark.createDataFrame([("1","1664968"),("2","3"),("2","742a7"),("2"," "),("2","a")],["From","To"])
df.show()
#+----+-------+
#|From|     To|
#+----+-------+
#|   1|1664968|
#|   2|      3|
#|   2|  742a7|
#|   2|       |
#|   2|      a|
#+----+-------+
#get the rows which have space or word in them
df.filter(col("To").rlike('([a-z]|\s+)')).show(truncate=False)
#+----+-----+
#|From|To   |
#+----+-----+
#|2   |742a7|
#|2   |     |
#|2   |a    |
#+----+-----+
#to get rows which doesn't have any space or word in them.
df.filter(~col("To").rlike('([a-z]|\s+)')).show(truncate=False)
#+----+-------+
#|From|To     |
#+----+-------+
#|1   |1664968|
#|2   |3      |
#+----+-------+

最新更新