Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does trying to add a row to a dataframe yield the error of the truth value of the dataframe being ambiguous

I have some testing code as shown below:

res = pd.DataFrame(columns=[0, 1, 2, 3, 4])
res.loc[len(res)] = pd.DataFrame([5, 6, 7, 8, 9])

But it causes this error to be shown:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But len(res) is simply a number and not a boolean mask, so its not and and & and or | thing causing the error like what I saw on SO when I searched the error…

>Solution :

You need to assign a Series (or list) as it’s 1D, not a DataFrame that is 2D:

res.loc[len(res)] = pd.Series([5, 6, 7, 8, 9])

# or
# res.loc[len(res)] = [5, 6, 7, 8, 9]

print(res)

Output:

   0  1  2  3  4
0  5  6  7  8  9
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading