通过取两个现有列的比率在数据框中添加新列

时间:2018-10-08 13:55:00

标签: pandas dataframe

我想通过采用两个现有列的比率在数据框中创建一个新列。以下代码可以工作,但不保留df [price_per_sqft]列。

df['price_per_sqft'] = (df['SalePrice']/df['LotArea'])

2 个答案:

答案 0 :(得分:0)

这应该做:

df['price_per_sqft'] = df['SalePrice']/df['LotArea']

或者您可以使用pd.assign

df.assign(price_per_sqft = df.SalePrice/df.LotArea)

答案 1 :(得分:0)

您的代码看起来还不错。它会在python3中工作,只是会引发如下警告:

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  #!/home/ubuntu/python_env/.env_quantz_tools/bin/python3.5

只需将其从支架中取出,就可以了。

df['price_per_sqft'] = df['SalePrice']/df['LotArea']