将逗号分隔的字符串转换为pyspark数据帧中的数组 [英] Convert comma separated string to array in pyspark dataframe

查看:20
本文介绍了将逗号分隔的字符串转换为pyspark数据帧中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的数据框,其中 ev 是字符串类型.

<预><代码>>>>df2.show()+---+--------------+|身份证|ev|+---+--------------+|1|200, 201, 202||1|23、24、34、45||1|空||2|32||2|空|+---+--------------+

有没有办法在不使用 UDF 的情况下将 ev 转换为 ArrayType 类型,或者 UDF 是唯一的选择?

解决方案

您可以使用内置的 split 功能:

from pyspark.sql.functions import col, splitdf = 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"))

如果要将数据转换为数字类型,可以按如下方式进行转换:

df.withColumn("ev",split(col("ev"), ",\s*").cast("array").alias("ev"))

from pyspark.sql.types import ArrayType, IntegerTypedf.withColumn("ev",split(col("ev"), ",\s*").cast(ArrayType(IntegerType())).alias("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|
+---+--------------+

Is there a way to cast ev to type ArrayType without using UDF or UDF is the only option to do that?

解决方案

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")
)

or

from pyspark.sql.types import ArrayType, IntegerType

df.withColumn(
    "ev",
    split(col("ev"), ",\s*").cast(ArrayType(IntegerType())).alias("ev")
)

这篇关于将逗号分隔的字符串转换为pyspark数据帧中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆