将逗号分隔的字符串转换为pyspark数据帧中的数组 [英] Convert comma separated string to array in pyspark dataframe
本文介绍了将逗号分隔的字符串转换为pyspark数据帧中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的数据框,其中ev是字符串类型.
I have a dataframe as below where ev is of type string.
>>> df2.show()
+---+--------------+
| id| ev|
+---+--------------+
| 1| 200, 201, 202|
| 1|23, 24, 34, 45|
| 1| null|
| 2| 32|
| 2| null|
+---+--------------+
有没有一种方法可以在不使用UDF的情况下将ev转换为ArrayType?或者是唯一的选择?
Is there a way to cast ev to type ArrayType without using UDF or UDF is the only option to do that?
推荐答案
您可以使用内置的split
函数:
You can use built-in split
function:
from pyspark.sql.functions import col, split
df = sc.parallelize([
(1, "200, 201, 202"), (1, "23, 24, 34, 45"), (1, None),
(2, "32"), (2, None)]).toDF(["id", "ev"])
df.select(col("id"), split(col("ev"), ",\s*").alias("ev"))
如果要将数据转换为数字类型,可以按如下所示进行转换:
If you want to convert data to numeric types you can cast as follows:
df.withColumn(
"ev",
split(col("ev"), ",\s*").cast("array<int>").alias("ev")
)
或
from pyspark.sql.types import ArrayType, IntegerType
df.withColumn(
"ev",
split(col("ev"), ",\s*").cast(ArrayType(IntegerType())).alias("ev")
)
这篇关于将逗号分隔的字符串转换为pyspark数据帧中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文