PySpark写的CSV报价都是非数字的

问题描述 投票:1回答:1

使用df.write.csv('path')输出到CSV文件时,有没有办法只引用数据框中的非数字列?

我知道你可以使用选项quoteAll=True来引用所有列,但我只想引用字符串列。

我正在使用PySpark 2.2.0。

csv apache-spark pyspark quote
1个回答
1
投票

我只想引用字符串列。

write.csv目前没有参数可用于指定要引用的列。但是,一种解决方法是通过在值周围添加引号来修改字符串列。

首先通过迭代dtypes来识别字符串列

string_cols = [c for c, t in df.dtypes if t == "string"]

现在,您可以通过添加引号作为前缀和后缀来修改这些列:

from pyspark.sql.functions import col, lit, concat

cols = [
    concat(lit('"'), col(c), lit('"')) if c in string_cols else col(c) 
    for c in df.columns
]

df = df.select(*cols)

最后写出csv:

df.write.csv('path')
© www.soinside.com 2019 - 2024. All rights reserved.