DDN
DDN

Reputation: 1

Error message when using Pandas sort values in place

density is a pandas Series :

density=data2010['density']
density.head()
state  
Alabama        91.287603  
Alaska          1.087509  
Arizona        56.214497  
Arkansas       54.948667  
California    228.051342  
Name: density, dtype: float64  

I am trying to sort out the values using inplace=True

 density.sort_values(ascending=False, inplace=True)

But somehow I got an error message:

ValueError: This Series is a view of some other array, to sort in-place you must create a copy

Could you please help / explain?

Note that the book I am learning from did the same steps as I did and no error, so I am guessing it is an issue of a newer version of Pandas.

Upvotes: 0

Views: 598

Answers (3)

Renaud
Renaud

Reputation: 2819

I had this issue one time, and I manage with using .copy():

density=data2010['density'].copy()
density.sort_values(ascending=False, inplace=True)

(edit: explanation added) If you don't use copy you are just creating a view to the original data. If you then ask for an "inplace=True" sorting, it is not clear what you really like to have sorted (the view, the original data or both). This is why the compiler throw the error.

Upvotes: 1

Kurt Kline
Kurt Kline

Reputation: 2069

Try this:

density = density2010['density'].copy()

Upvotes: 0

hyamanieu
hyamanieu

Reputation: 1115

make a copy.

density=data2010.copy()['density']

Upvotes: 0

Related Questions