The logic of the two codes are not the same. The second code should be what you wanted. In the first code you selected duplicated columns because select
does not overwrite columns, but withColumn
does.
import pyspark.sql.functions as func
char_list = [('\\', '\\\\'), ('
', '\\n'), (''', '\\'')]
col_names = df.schema.names
df = spark.createDataFrame([['1','2']])
print(len(df.select( *[func.regexp_replace(col_name, char_set[0], char_set[1]) for char_set in char_list for col_name in col_names]).columns))
# gives 6
df = spark.createDataFrame([['1','2']])
for char_set in char_list:
for col_name in col_names:
df = df.withColumn(col_name, func.regexp_replace(col_name, char_set[0], char_set[1]))
print(len(df.columns))
# gives 2
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…