简体   繁体   English

pandas单元测试AssertionError: DataFrame.index不同

[英]pandas unit test AssertionError: DataFrame.index are different

I have this function that I want to test:我有这个 function 我想测试:

def filter_df(df, column_name: str, skill: List):
    return df.query(f"{column_name} in {skill}")

This is my test:这是我的测试:

def test_filter_df():
    df = pd.DataFrame({"col1": ["sap", "hi", "abc"], "col2": [3, 4, 4]})
    expected = pd.DataFrame({"col1": ["hi", "abc"], "col2": [4, 4]})
    assert_frame_equal(filter_df(df, "col1", ["hi", "abc"]), expected)

I'm getting a assert_frame_equal(filter_df(df, "col1", ["hi", "abc"]), expected) error, but I don't see why the dataframes aren't identical.我收到assert_frame_equal(filter_df(df, "col1", ["hi", "abc"]), expected)错误,但我不明白为什么数据帧不相同。

You need to reset the index in filter_df :您需要重置filter_df中的索引:

df.query(f"{column_name} in {skill}").reset_index(drop=True)

At the moment the returned DF has the original index of the given rows which in your case is 1,2 and not 0,1 as in the expected DF目前返回的 DF 具有给定行的原始索引,在您的情况下是 1,2 而不是expected DF 中的 0,1

Alternatively, if this is intended behavior of the function, edit the expected DF to have the correct index或者,如果这是 function 的预期行为,请编辑expected的 DF 以具有正确的索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 pandas dataframe.index 中没有重复项? - Why is there no duplicates in pandas dataframe.index? Python Pandas:dataframe.loc返回“ KeyError:标签不在[index]中”,但dataframe.index显示它是 - Python Pandas: dataframe.loc returns “KeyError: label not in [index]”, but dataframe.index shows it is 在带有条件的DataFrame.index中找到最小值 - find minimum in DataFrame.index with condition 如何从对象类型为 datetime.time 的 Pandas DataFrame.Index 添加/减去时间(小时、分钟等)? - How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? pandas 数据帧索引错误:AssertionError:索引和值的长度不匹配 - pandas dataframe index error: AssertionError: Lengths of index and values did not match 透视pandas DataFrame - AssertionError:索引长度与值不匹配 - Pivoting pandas DataFrame — AssertionError: Index length did not match values pandas concat DataFrame对不同的索引 - pandas concat DataFrame on different Index Pandas DataFrame:测试是否设置了索引名称 - Pandas DataFrame: test if index name is set 当我尝试进行单元测试时AssertionError - AssertionError when I try to conduct a unit test 如何修复单元测试中的错误? | 断言错误 - How fix error in unit test? | AssertionError
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM