Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two piece of codes below having same logic, curious to know which one is better of two and why?

1.

char_list = [('\\', '\\\\'), ('
', '\\n'), (''', '\\'')]
col_names = df.schema.names
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])
char_list = [('\\', '\\\\'), ('
', '\\n'), (''', '\\'')]
col_names = df.schema.names
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]))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...