在pyspark dataframe中用双引号替换单引号

2024-10-01 09:18:57 发布

您现在位置:Python中文网/ 问答频道 /正文

根据下面的代码,我正在将数据帧写入csv文件

由于我的数据帧包含None"",我添加了replace("", None),因为Null值应该表示为None,而不是""(双引号)

newDf.coalesce(1).replace("", None).replace("'", "\"").write.format('csv').option('nullValue', None).option('header', 'true').option('delimiter', '|').mode('overwrite').save(destination_csv)

我尝试添加.replace("'", "\"").,但没有效果

该数据还包含带单引号的数据

例如:

Survey No. 123, 'Anjanadhri Godowns', CityName

我需要替换数据帧中的单引号,并将其替换为双引号

如何实现这一目标


Tags: 文件csv数据代码noneformatnullreplace
2条回答

在写入输出之前,可以使用regexp_replace将所有列中的单引号替换为双引号:

import pyspark.sql.functions as F

df2 = df.select([F.regexp_replace(c, "'", '"').alias(c) for c in df.columns])

# then write output
# df2.coalesce(1).write(...)

使用^{}

from pyspark.sql.functions import *

data_list = [(1, "'Name 1'"), (2, "'Name 2' and 'Something'")]
df = spark.createDataFrame(data = data_list, schema = ["ID", "my_col"])
# + -+          +
# | ID|              my_col|
# + -+          +
# |  1|            'Name 1'|
# |  2|'Name 2' and 'Som...|
# + -+          +

df.withColumn('my_col', translate('my_col', "'", '"')).show()
# + -+          +
# | ID|              my_col|
# + -+          +
# |  1|            "Name 1"|
# |  2|"Name 2" and "Som...|
# + -+          +

这将在my_col列中用双引号替换所有出现的单引号字符

相关问题 更多 >