簡體   English   中英

如何使用pyspark在Spark DataFrame中解壓縮列

[英]How to unzip a column in a Spark DataFrame using pyspark

我正在使用帶有壓縮列的數據框。 我想使用zlib.decompress將其解壓縮。 以下代碼段是我的嘗試:

from zlib import decompress
from pyspark.sql.functions import udf
toByteStr = udf(bytes)
unzip = udf(decompress)
df = (spark.read.format("xx.xxx.xx.xx").
  load())
df1 = df.withColumn("message", unzip(toByteStr("content"), 15+32))

以下消息是我得到的錯誤:

An error occurred while calling z:org.apache.spark.sql.functions.col. Trace:
py4j.Py4JException: Method col([class java.lang.Integer]) does not exist
    at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:318)
    at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:339)
    at py4j.Gateway.invoke(Gateway.java:274)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:748)
Traceback (most recent call last):

我真的需要您的幫助來解決。 謝謝。

更多信息:

我只是意識到實際數據是以pkzip格式壓縮的,而zlib不支持該格式。 我正在嘗試使用以下代碼將其解壓縮。

import StringIO
import zipfile
from pyspark.sql.functions import udf

def unZip(buf):
    fio = StringIO.StringIO(buf)
    z = zipfile.ZipFile(fio, 'r')
    result = z.open(z.infolist()[0]).read()
    return result

toByteStr = udf(bytes, StringType())
unzip = udf(unZip, StringType())

df = (spark.read.format("xxx.xxx.xxx.xx").
  option("env", "xxx").
  option("table", "xxxxx.xxxxxx.xxxx").
  load())

df1 = df.withColumn("message", unzip(toByteStr("content")))
df1.show()

我用Zip字符串嘗試了“ unZip ”功能,它很好用。 但是,當我想注冊為udf並在Spark Cluster上並行工作時,它顯示的文件不是zip文件,但我確定是。 錯誤如下:

BadZipfile: File is not a zip file
    at 
org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:193)
at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:234)
at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:152)
at org.apache.spark.sql.execution.python.BatchEvalPythonExec$$anonfun$doExecute$1.apply(BatchEvalPythonExec.scala:144)
at org.apache.spark.sql.execution.python.BatchEvalPythonExec$$anonfun$doExecute$1.apply(BatchEvalPythonExec.scala:87)
at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1$$anonfun$apply$23.apply(RDD.scala:797)
at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1$$anonfun$apply$23.apply(RDD.scala:797)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)

第二個參數也應該是Column ,因此您需要使用lit函數:

from pyspark.sql.functions import lit

df.withColumn("message", unzip(toByteStr("content"), lit(15 + 32)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM