I tried this below code to get the top 5 in column G.
Ndata = data.sort_values( 'G', ascending=False)
newcol = Ndata.loc[:, 'G'].nlargest(5)
newcol
However, I am wondering, how do I get this code work to get the corresponding columns A, B and C.?
CodePudding user response:
You can directly use nlargest
on the data frame and specify which column you want to take values from. Example:
df = pd.DataFrame({'a': [1,2,3,4,5], 'b': [5,4,3,2,1]})
df.nlargest(n=3, columns='a')
a b
4 5 1
3 4 2
2 3 3
In your case:
data.nlargest(n=5, columns='G')
should work.