【问题标题】:Performing functions on multiple columns in Pyspark dataframes在 Pyspark 数据框中的多列上执行函数
【发布时间】: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


【解决方案1】:

对于 multiple filters,您应该这样做。

filter_cols= ['account_id','phone_number','credit_card_number','credit_card_limit','transaction_code','amount']
    
final_df.filter(' and '.join([x+' is not null' for x in  filter_cols]))

【讨论】:

  • 非常感谢您的帮助!我得到了结果。 'and' 是否会导致使用那个 'x+' 执行多个过滤条件?
  • 是的,你可以打印' and '.join([x+' is not null' for x in filter_cols])来检查它给出的sql表达式
猜你喜欢
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
相关资源
最近更新 更多