【问题标题】:Masking credit card number using PySpark使用 PySpark 屏蔽信用卡号
【发布时间】:2020-06-30 14:02:42
【问题描述】:

我是 Spark 的新手,我需要屏蔽 Spark 数据框中的信用卡号,其中仅显示最后四位数字。该怎么做?

下面是我的桌子

    +----------+------------+
    |first_name|        card|
    +----------+------------+
    |       abc|999999999999|
    |       lmn|222222222222|
    +----------+------------+

预期输出:

    +----------+------------+
    |first_name|        card|
    +----------+------------+
    |       abc|********9999|
    |       lmn|********2222|
    +----------+------------+

【问题讨论】:

    标签: apache-spark hadoop pyspark apache-spark-sql


    【解决方案1】:

    在 pyspark 中也可以使用 substring 函数

    from pyspark.sql.types import *
    tst= sqlContext.createDataFrame([("name1",9999999999),("name2",2222222222)],schema=['name','number'])
    # This is assuming your card number is not a string. If not skip this cast
    tst_cast = tst.withColumn("number_string",F.col('number').cast(StringType()))
    tst_mask = tst_cast.withColumn("masked_number",F.concat(F.lit('******'),F.substring(F.col("number_string"),6,4)))
    

    【讨论】:

      【解决方案2】:
      Seq("123456789").toDF()
      .select(concat(lit("********"),regexp_extract('value',".{4}$",0)).as("card"))
      .show()
      
      +------------+
      |        card|
      +------------+
      |********6789|
      +------------+
      

      【讨论】:

        【解决方案3】:

        您可以同时使用 substring 和 lpad 来生成类似的行为,

        df.selectExpr("lpad(substring(card,length(card)-4,4),16,'*') as card").show()
        
        +----------------+
        |            card|
        +----------------+
        |************9999|
        +----------------+
        
        
        

        【讨论】:

          【解决方案4】:

          另一种选择-

            df.withColumn("masked_cc", expr("concat(translate(left(card, length(card)-4), '0123456789', '**********')," +
                "right(card, 4))"))
                .show(false)
          
              /**
                * +----------+------------+------------+
                * |first_name|card        |masked_cc   |
                * +----------+------------+------------+
                * |abc       |999999999999|********9999|
                * |lmn       |222222222222|********2222|
                * +----------+------------+------------+
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-12-25
            • 2011-11-20
            • 2023-03-13
            • 2017-10-19
            • 2011-11-11
            • 1970-01-01
            相关资源
            最近更新 更多