Home > Software engineering >  In Python, what is the difference between df["row_name"] and df.loc["row_name"]
In Python, what is the difference between df["row_name"] and df.loc["row_name"]

Time:11-21

I am trying to add another row to my data Frame

When I use df["new_row"] = [5, True, "joe", 20] , I get the error

ValueError: Length of values (4) does not match length of index (11)

but if I use df.loc["new_row"] = [5, True, "joe", 20], I can succesfully add a new row.

CodePudding user response:

This post may contain the detailed explanation you are searching for. Found a link which you might find helpful

CodePudding user response:

To answer your question about the difference, in pandas, df["colname"] is used to access a column of a given data frame.

loc[r,c] is used to access specific cells within that data frame in the order of row and column. So, if you use df.loc[r], it will access the entire row.

In your case,df.loc['new_row'], creates a new row, at which you are inserting [5, True, "joe", 20]

  • Related