【问题标题】:How to do string transformation in pyspark?如何在pyspark中进行字符串转换?
【发布时间】:2017-05-17 07:23:00
【问题描述】:

我有这样的数据。我想将 low 列转换为整数。例如,如果是01:23.0,我希望它是 1*60 + 23 = 83。

如何做到这一点?我试过udf,但它引发了Py4JJavaError

df = sqlContext.createDataFrame([
    ('01:23.0', 'z', 'null'), 
    ('01:23.0', 'z', 'null'),  
    ('01:23.0', 'c', 'null'),
    ('null', 'null', 'null'),  
    ('01:24.0', 'null', '4.0')],
    ('low', 'high', 'normal'))

    def min2sec(v):
        if pd.notnull(v):
            return int(v[:2]) * 60 + int(v[3:5])

    udf_min2sec = udf(min2sec, IntegerType())
    df.withColumn('low', udf_min2sec(df['low'])).show() 

【问题讨论】:

    标签: python python-2.7 apache-spark pyspark udf


    【解决方案1】:

    您不需要udf,您可以使用内置函数来达到您的预期输出:

    from pyspark.sql.functions import split, col
    
    df.withColumn("test", split(col("low"),":").cast("array<int>")) \
      .withColumn("test", col("test")[0]*60 + col("test")[1]).show()
    +-------+----+------+----+
    |    low|high|normal|test|
    +-------+----+------+----+
    |01:23.0|   z|  null|  83|
    |01:23.0|   z|  null|  83|
    |01:23.0|   c|  null|  83|
    |   null|null|  null|null|
    |01:24.0|null|   4.0|  84|
    +-------+----+------+----+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 2016-03-16
      • 2018-02-02
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多