我有一个包含两个数字列的数据,A& B。我想从col中找到前5位的值,并返回位于前5位的Col B的值。
非常感谢。
发布于 2018-05-12 08:05:11
我认为前5行需要DataFrame.nlargest和A列,然后选择列B
df = pd.DataFrame({'A':[4,5,26,43,54,36,18,7,8,9],
'B':range(10)})
print (df)
A B
0 4 0
1 5 1
2 26 2
3 43 3
4 54 4
5 36 5
6 18 6
7 7 7
8 8 8
9 9 9print (df.nlargest(5, 'A'))
A B
4 54 4
3 43 3
5 36 5
2 26 2
6 18 6
a = df.nlargest(5, 'A')['B']
print (a)
4 4
3 3
5 5
2 2
6 6
Name: B, dtype: int64有排序的替代解决方案:
a = df.sort_values('A', ascending=False)['B'].head(5)
print (a)
4 4
3 3
5 5
2 2
6 6
Name: B, dtype: int64发布于 2018-05-12 08:07:06
nlargest函数在dataframe上完成您的工作,df.nlargest(#of rows,'column_to_sort')
import pandas
df = pd.DataFrame({'A':[1,1,1,2,2,2,2,3,4],'B':[1,2,3,1,2,3,4,1,1]})
df.nlargest(5,'B')
Out[13]:
A B
6 2 4
2 1 3
5 2 3
1 1 2
4 2 2
# if you want only certain column in the output, the use
df.nlargest(5,'B')['A']https://stackoverflow.com/questions/50304103
复制相似问题