【发布时间】:2020-07-13 14:36:55
【问题描述】:
我必须在 Pyspark dataframe 中的多个列上应用某些函数。以下是我的代码:
finaldf=df.withColumn('phone_number',regexp_replace("phone_number","[^0-9]",""))\
.withColumn('account_id',regexp_replace("account_id","[^0-9]",""))\
.withColumn('credit_card_limit',regexp_replace("credit_card_limit","[^0-9]",""))\
.withColumn('credit_card_number',regexp_replace("credit_card_number","[^0-9]",""))\
.withColumn('full_name',regexp_replace("full_name","[^a-zA-Z ]",""))\
.withColumn('transaction_code',regexp_replace("transaction_code","[^a-zA-Z]",""))\
.withColumn('shop',regexp_replace("shop","[^a-zA-Z ]",""))
finaldf=finaldf.filter(finaldf.account_id.isNotNull())\
.filter(finaldf.phone_number.isNotNull())\
.filter(finaldf.credit_card_number.isNotNull())\
.filter(finaldf.credit_card_limit.isNotNull())\
.filter(finaldf.transaction_code.isNotNull())\
.filter(finaldf.amount.isNotNull())
从代码中您可以看到我编写的冗余代码也延长了程序的长度。我还了解到 spark UDF 效率不高。
有没有办法优化这段代码?请告诉我。非常感谢!
【问题讨论】:
-
您可以将所有这些条件放在一个语句中:
.filter(finaldf.account_id.isNotNull() & finaldf.phone_number.isNotNull() & ...) -
好的,谢谢!有没有办法使用单个循环来完成所有这些常见功能?
标签: apache-spark pyspark apache-spark-sql pyspark-dataframes