user3120266 user3120266 - 7 months ago 30
Python Question

Adding columns in pandas

I am working with some housing data in python. I am trying to calculate price in sq feet and add it to the dataframe. I am able to do the calculation alone, but when I try to add the column back to the dataframe, I keep receiving an error.

Code:

price_feet=[data['price']/data['sqft_living']]


This works on it own

This does not

data['price_feet']=[data['price']/data['sqft_living']]


Error received:
Length of values does not match length of index

I assume that there is not a match in the data with the two variables. This is why I am able to do the calculation but not add it back to the dataframe. I have tried looking up some answers but apparently haven't found the right fix yet.

Thanks!

Answer

Try it without the brackets:

data['price_feet']=data['price']/data['sqft_living']

The square brackets were returning a list where the first item was a series. You just want the series.