如何在pyspark中处理数据科学问题的异常

fslejnso  于 2021-05-27  发布在  Spark
关注(0)|答案(2)|浏览(261)

如何识别以下重命名列将产生哪种异常以及如何在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'}")

如何通过使用数据集生成异常来测试它。

sbdsn5lh

sbdsn5lh1#

我找到了这个问题的解决方案,我们可以像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)
2q5ifsrm

2q5ifsrm2#

下面是一个如何测试抛出异常的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 函数并验证错误消息是否符合预期。
其他一些提示:
按照示例在此处和此处重命名列。你不应该打电话 withColumnRenamed 在一个循环中。
使用标准转换格式编写Dataframe转换,以便它们可以与Dataframe转换链接
使用pytest descripe组织这些类型的测试
请查看这个测试文件以获得一组示例

相关问题