0
$\begingroup$

I am using pytest to test a function that reads a csv into a dictionary of lists. In the test function it writes a sample dictionary to a csv then calls the function to read it back out. To accomplish this the df.to_csv() has to have the index=False parameter to avoid writing the index then reading it as an unnamed column.

I get the error 'ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()' when I run the test function.

I have confirmed that the read function operates correctly. Here is the code:

def read_csv(filename):
    """Read the contents of a CSV file into a compound
    dictionary and return the dictionary.
    """
    # Read the csv file and input it into a dictionary
    reader = pd.read_csv(filename)
        
    return reader

and the subsequent test function:

def test_read_csv():
    """Verify that the read_csv function works correctly"""
    # Wrie a sample csv file
    filename = 'test.csv'
    # Information for the header of the file
    # the items in the list.
    temp_dict = {
        'product': [1, 2, 3],
        'quantity': [15, 25, 40]
    }
    # opens the file and writes the provided information to it.
    writer = pd.DataFrame.from_dict(temp_dict)
    # Send the dataframe to a csv
    writer.to_csv(filename, index=False)

    # Call read_csv to read the sample file
    read = read_csv(filename)

    # Delete the lines.csv file
    os.remove(filename)

    # Verify that read_csv read the file correctly
    assert read == writer

How to I get this to work as needed.

$\endgroup$
2
  • 1
    $\begingroup$ To check if two dataframes are the same you probably want to use the pandas.DataFrame.equals method instead of using ==. $\endgroup$
    – Oxbowerce
    Jul 15, 2022 at 13:55
  • $\begingroup$ That fixed it thank you. $\endgroup$ Jul 15, 2022 at 15:41

1 Answer 1

0
$\begingroup$

The two data frames do not reference to same object,in case of pandas the normal python boolean logic statement's doesn't work. But your problem can with a little change
so change your this part of code

    # Verify that read_csv read the file correctly
    assert read == writer

To,

    # Verify that read_csv read the file correctly
    assert read.equals(writer)

equals function will check all the elements of two dara Hope it helps

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.