【问题标题】:How to handle exception in Pyspark for data science problems如何在 Pyspark 中处理数据科学问题的异常
【发布时间】:2020-07-31 10:15:08
【问题描述】:

如何识别重命名列下面会出现哪种异常以及如何在 pyspark 中处理它:

def rename_columnsName(df, columns):   #provide names in dictionary format
if isinstance(columns, dict):     
    for old_name, new_name in columns.items():
        df = df.withColumnRenamed(old_name, new_name)
    return df.show()
else:
    raise ValueError("'columns' should be a dict, like {'old_name':'new_name', 'old_name_one more':'new_name_1'}")

如何通过使用数据集生成异常来对其进行测试。

【问题讨论】:

  • 你想做什么处理?如果该列存在,也许您可​​以在调用 withColumnRenamed 之前进行检查?这将允许您对负面情况进行必要的处理并单独处理这些情况。

标签: python apache-spark pyspark data-science


【解决方案1】:

这是一个如何测试引发异常的 PySpark 函数的示例。在此示例中,我们正在验证如果排序顺序为 "cats" 则引发异常。

def it_throws_an_error_if_the_sort_order_is_invalid(spark):
    source_df = spark.create_df(
        [
            ("jose", "oak", "switch"),
            ("li", "redwood", "xbox"),
            ("luisa", "maple", "ps4"),
        ],
        [
            ("name", StringType(), True),
            ("tree", StringType(), True),
            ("gaming_system", StringType(), True),
        ]
    )
    with pytest.raises(ValueError) as excinfo:
        quinn.sort_columns(source_df, "cats")
    assert excinfo.value.args[0] == "['asc', 'desc'] are the only valid sort orders and you entered a sort order of 'cats'"

请注意,该测试正在验证所提供的特定错误消息。

您可以向rename_columnsName 函数提供无效输入,并验证错误消息是否符合您的预期。

其他一些提示:

【讨论】:

    【解决方案2】:

    我找到了这个问题的解决方案,我们可以像 python 一样在 Pyspark 中处理异常。 例如:

    def rename_columnsName(df, columns):#provide names in dictionary format
    try:
    
       if isinstance(columns, dict):
          for old_name, new_name in columns.items():     
        
               df = df.withColumnRenamed(old_name, new_name)
    return df.show()
       else:
             raise ValueError("'columns' should be a dict, like {'old_name':'new_name', 
                    'old_name_one more':'new_name_1'}")
    except Exception as e:
          print(e)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-24
      • 2011-11-19
      • 1970-01-01
      • 2016-06-27
      相关资源
      最近更新 更多