Home > database >  Why does trying to add a row to a dataframe yield the error of the truth value of the dataframe bein
Why does trying to add a row to a dataframe yield the error of the truth value of the dataframe bein

Time:01-28

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().

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...

CodePudding user response:

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
  • Related