【问题标题】:How do I unit test or use assert on a dataframe?如何对数据框进行单元测试或使用断言?
【发布时间】:2019-05-21 06:30:32
【问题描述】:

我想对我的代码进行单元测试,以确保代码的输出是正确的。

我也从 StackOverflow 尝试过,但没有工作:

input = pd.DataFrame.from_dict({
    'rev': [0],
    'price': [0]
})
expected = {
    'data': ['cool']
}

assert_dict_equal(expected, data(input).to_dict(),
                  "oops, there's a bug...")


def temperature(row):
    rev = row['rev']
    price = row['price']
    group = row['group']
    if group == 'error':
        return 'error'
    elif revenue > 2 * price:
        return 'cold'
    elif revenue >= price:
        return 'cool'
    elif revenue < 0.5 * price:
        return 'hot'
    elif revenue < price:
        return 'lukewarm'
    else:
        float('NA')

data['temp'] = sample.apply(temperature, axis=1)

assert temperature({"group": 'T2_Y2', "rev": 0, "price": 0}, 
                        "group", "rev", "price") == 'cool'

assert temperature({"group": 'T2_Y2', "rev": 30, "price": 10}, 
                        "group", "rev", "price") == 'cold'

assert temperature({"group": 'T2_Y2', "rev": 3, "price": 10}, 
                        "group", "rev", "price") == 'hot'

当输出给出错误时,预期的结果应该返回而没有错误。

TypeError: temperature() 接受 1 个位置参数,但给出了 4 个

【问题讨论】:

  • 请提供您看到的完整错误回溯
  • 实施编辑修正后仍然报错。这是错误:TypeError: temperature() 需要 1 个位置参数,但给出了 4 个。

标签: python pandas unit-testing dataframe assert


【解决方案1】:

错误很明确:您试图在断言中使用 4 个位置参数调用 temperature 函数,而它只需要 1 个。用这些替换您的断言:

assert temperature({"group": 'T2_Y2', "rev": 0, "price": 0}) == 'cool'
assert temperature({"group": 'T2_Y2', "rev": 30, "price": 10}) == 'cold'
assert temperature({"group": 'T2_Y2', "rev": 3, "price": 10}) == 'hot'

编辑:根据您的评论,将您的功能更改为以下功能:

def temperature(row, group_col, rev_col, price_col):
    rev = row[rev_col]
    price = row[price_col]
    group = row[group_col]
    if group == 'error':
        return 'error'
    elif revenue > 2 * price:
        return 'cold'
    elif revenue >= price:
        return 'cool'
    elif revenue < 0.5 * price:
        return 'hot'
    elif revenue < price:
        return 'lukewarm'
    else:
        float('NA')

然后保持你的断言不变,它应该可以工作

【讨论】:

  • 那么如果取出其他三个参数,如何重构assert语句来测试代码呢?
  • 为什么你甚至想将 4 个参数传递给一个只需要 1 的函数?其他 3 个论点的目的是什么?在函数定义中你甚至不使用它们?你想做什么?
  • 它是一个DataFrame,其他三个参数是DataFrame中的列。我想测试/检查如果我在 DataFrame 的一行中有这些值,它将返回正确的结果/温度。
  • 查看我编辑的答案。您可能需要添加一些检查,例如 if group_col in row 以确保您的代码不会引发 KeyError
猜你喜欢
  • 1970-01-01
  • 2019-09-23
  • 2021-06-22
  • 2011-08-17
  • 1970-01-01
  • 2020-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多