Home > Net >  How to copy the largest values from me older dataframe to new using pandas?
How to copy the largest values from me older dataframe to new using pandas?

Time:11-30

my sort_drop2 dataframe is shown in the picture below

https://imgur.com/a/mdZZa7n

new_dataframe = sort_drop2.filter(['City','Est','Nti']

sort_drop2.filer I am trying to copy specific details from the old dataset into a new dataframe.

I want to only take the top 5 values from the sort_drop2 dataframe

I have sorted the sort_drop2 by nti from largest to smaller sort_values(by='Nti', ascending=False)

How do I copy only the top 5 values from the old dataframe to new?

CodePudding user response:

You can get the top n rows of dataframe df with df.head(n). So in your case, take your sorted and filtered dataframe do do:

new_dataframe.head(5)

The default for n is 5, so you could also leave the parameter blank.

That will return the dataframe. If you want to save something new as it, you would do:

df_top_5 = new_dataframe.head(5)

CodePudding user response:

Use .head(5) on the old DataFrame sort_drop2 and assign the result to your new DataFrame like this:

new_dataframe = sort_drop2.filter(['City','Est','Nti']).sort_values(by='Nti', ascending=False).head(5)

Here's my answer expanded over multiply lines which is more similar to your code you described so perhaps the following answer will be easier to compare to your existing code:

new_dataframe = sort_drop2.filter(['City','Est','Nti'])

new_dataframe = new_dataframe.sort_values(by='Nti', ascending=False)

new_dataframe = new_dataframe.head(5)
  • Related