首页 > 解决方案 > Pandas how to copy column from one DataFrame to another with specific

问题描述

I created DataFrame1 using Pandas.

books_input = {"author_id" : [1, 1, 1, 2, 2, 3, 3],
               "book_title" : ['Отцы и дети', 'Рудин', 'Дворянское гнездо', 'Толстый и тонкий', 'Дама с собачкой', 'Гроза', 'Таланты и поклонники'],
               "price" : [450, 300, 350, 500, 450, 370, 290]}

DataFrame1 = pd.DataFrame(books_input)

I need to create new DataFrame called top5 and I need to take 5 highest values from "price" column from DataFrame1(need to show the most expensive books).

How I can do it? Using merging? If yes, then how I can show merge this column with specific restrictions(only 5 values)?

标签: pythonpandas

解决方案


您可以使用.nlargest()

import pandas as pd
top5 = pd.DataFrame([10,220,33,1,2,3], ["a","b","c",'x','x','x'], columns=['price'])
top5['price'].nlargest(n=5, keep='first')

Out[12]: 
b    220
c     33
a     10
x      3
x      2
Name: value, dtype: int64

推荐阅读