python - 在 Python 中找到第二和第三高的值

标签 python python-3.x pandas

我有以下食品数据框及其营养成分如下:

import pandas as pd
import os
os.chdir('D:\\userdata\\adbharga\\Desktop\\AVA\\RTestCode\\Python')
data=pd.read_csv("nutrient.csv")
data.head()

输出[30]:

Name  Calories  Fat  Carb  Fiber  Protein
0      Chonga Bagel       300    5    50      3       12
1      8-Grain Roll       380    6    70      7       10
2  Almond Croissant       410   22    45      3       10
3     Apple Fritter       460   23    56      2        7
4  Banana Nut Bread       420   22    52      2        6

需要提取Top Nutrient的含量及其值(value)。对于下面使用的代码。

data['Top Nutrient'] = data[['Calories','Fat','Carb','Fiber','Protein']].idxmax(axis=1)
data['Amount']= data[['Calories','Fat','Carb','Fiber','Protein']].max(axis=1)
data.head()

输出[33]:

Name  Calories  Fat  Carb  Fiber  Protein Top Nutrient  Amount
0      Chonga Bagel       300    5    50      3       12     Calories     300
1      8-Grain Roll       380    6    70      7       10     Calories     380
2  Almond Croissant       410   22    45      3       10     Calories     410
3     Apple Fritter       460   23    56      2        7     Calories     460
4  Banana Nut Bread       420   22    52      2        6     Calories     420

有没有办法显示下 2 个顶级营养素及其值(value)。预期输出将是这样的:

Name    NextTop2   NextTop2Amount
Chonga Bagel        Carb|Protein    50|12
8-Grain Roll        Carb|Protein    70|10
Almond Croissant    Carb|Fat        45|22
Apple Fritter       Carb|Fat        56|23
Banana Nut Bread    Carb|Fat        52|22

谢谢

最佳答案

这里最好用numpy.argsort因为非常快。

首先按 subset - [] 过滤列,然后按 argsort 为 2. 和 3. top 获取索引:

cols = ['Calories','Fat','Carb','Fiber','Protein']

arr = data[cols].values.argsort(axis=1)[:, [-2, -3]]
a = np.array(cols)[arr]
print (a)
[['Carb' 'Protein']
 ['Carb' 'Protein']
 ['Carb' 'Fat']
 ['Carb' 'Fat']
 ['Carb' 'Fat']]

也可以按索引选择值:

b = data[cols].values[np.arange(len(arr))[:,None], arr]
print (b)
[[50 12]
 [70 10]
 [45 22]
 [56 23]
 [52 22]]

最后创建 DataFrame 并通过 | 为一列添加连接:

data['Top Nutrient'] = data[cols].idxmax(axis=1)
data['Amount']= data[cols].max(axis=1)
data['NextTop2'] = pd.DataFrame(a).apply('|'.join, 1)
data['NextTop2Amount'] = pd.DataFrame(b).astype(str).apply('|'.join, 1)

print (data)

               Name  Calories  Fat  Carb  Fiber  Protein Top Nutrient  Amount  \
0      Chonga Bagel       300    5    50      3       12     Calories     300   
1      8-Grain Roll       380    6    70      7       10     Calories     380   
2  Almond Croissant       410   22    45      3       10     Calories     410   
3     Apple Fritter       460   23    56      2        7     Calories     460   
4  Banana Nut Bread       420   22    52      2        6     Calories     420   

       NextTop2 NextTop2Amount  
0  Carb|Protein          50|12  
1  Carb|Protein          70|10  
2      Carb|Fat          45|22  
3      Carb|Fat          56|23  
4      Carb|Fat          52|22  

关于python - 在 Python 中找到第二和第三高的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49153471/

相关文章:

python - 分数函数返回未减少的分数

python - 如何将 DataFrame 中的值与某些条件进行匹配?

python - 如何告诉 Numpy 以 UTC 而不是本地时区打印时间?

python - 尝试使用 opengl 函数 glMapBufferRange 在 python 中制作 alienrain

python - 如何在 Python 反汇编程序中访问堆栈的内容?

python - 如何使每个组的第一行作为pandas数据框中同一组中其他行的总和?

python - 当涉及无穷大值时, Pandas 滚动返回 NaN

php - 使用 PHP 检索 MySQL 多个查询并处理

python - 遍历 xarray 数据集中的 dataArray 属性

mysql - Python3 在cursor.execute之后它停止了?