Pyspark:使用Spark SFTP程序包时将数据帧转换为CSV,将数据帧的空白列写为“无”

问题描述

    test_df.limit(10).repartition(1).write.format("com.springml.spark.sftp").\
        option("host",sftp_host).\
        option("username",sftp_user).\
        option("password",sftp_pass).\
        option("fileType","csv"). \
        option("delimiter","|"). \
        option("codec","gzip"). \
        option("header","false"). \
    save(f"/test/{file_date}_{file_name}.txt.gz") 

以上代码以这种格式每行将数据写入csv文件。 (A |“” || B |“” | C)。但是,我希望将DataFrame编写为(A || B || C),其中用“无”值替换空引号。

找到了一种无需使用Spark SFTP程序包即可完成操作的方法,但无法弄清楚如何使用SPARK SFTP程序包并为空白列写“ None”。

参考文档:https://github.com/springml/spark-sftp

解决方法

您可以使用DataFrame na函数用所需的值替换任何空值或Nan值

>>> df = spark.createDataFrame([(1,"abc","test"),(2,None,"test1")],["col1","col2","col3"])
>>> df.show()
+----+----+-----+
|col1|col2| col3|
+----+----+-----+
|   1| abc| test|
|   2|null|test1|
+----+----+-----+

>>> df.na.fill("None",["col2"]).show()
+----+----+-----+
|col1|col2| col3|
+----+----+-----+
|   1| abc| test|
|   2|None|test1|
+----+----+-----+

https://spark.apache.org/docs/2.4.5/api/scala/index.html?org/apache/spark/sql/DataFrameNaFunctions.html#org.apache.spark.sql.DataFrameNaFunctions

https://spark.apache.org/docs/2.4.5/api/python/pyspark.sql.html#pyspark.sql.DataFrameNaFunctions.fill