Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

dataframe - How does for loop impact performance of spark code

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]))
question from:https://stackoverflow.com/questions/65834589/how-does-for-loop-impact-performance-of-spark-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...