熊猫通过值过滤df

时间:2018-07-26 13:44:21

标签: python python-3.x pandas

我有一个如下所示的df:

ID Component Avg
218 23a      1.88
218 12b      1.88
218 1e       4
530 2b       2.67
530 2d       2.55
231 1e       1
231 2d       1.67
689 1e       2.55
689 2b       4
689 3a       3
619 23b      1.67
619 12b      2

我需要获取ID的列表,其中任何Component的平均值均不低于2.51。

我尝试使用.loc和其他基本过滤,但是我不确定如何对每个Component的所有ID值进行迭代。

我想要的输出看起来像这样

ID
530
689

3 个答案:

答案 0 :(得分:0)

使用Avg获取每个ID的最大值groupby,然后对其进行过滤:

maxes = df.groupby("ID")["Avg"].max()
result = maxes[maxes["Avg"] < 2.51].index

答案 1 :(得分:0)

import pandas as pd
import numpy as np
# Make df
data = {'ID': [218, 218, 218, 530, 530, 231, 231, 689, 689, 689, 619, 619],
        'Component': ['23a', '12b', '1e', '2b', '2d', '1e', '2d', '1e', '2b', '3a', '23b', '12b'],
        'Avg': [1.88, 1.88, 4, 2.67, 2.55, 1, 1.67, 2, 4, 3, 1.67, 2]}
df = pd.DataFrame(data)
#Get lowest Average
pivot = pd.pivot_table(df,index='Component',values='Avg',aggfunc=min)

pivot=pivot.reset_index()

#Identify averages less than 2.51
pivot['Test'] = np.where(pivot['Avg']<2.51,1,0)

pivot=pivot.drop('Avg',axis=1)

df2=pd.merge(df,pivot,on='Component')

# Filter to passing components
df2[df2['Test']==0]

答案 2 :(得分:0)

您可以排除超出范围的ID:

exc = df.loc[df['Avg'] < 2.51, 'ID'].unique()
res = df['ID'][~df['ID'].isin(exc)].unique()

print(res)

array([530, 689], dtype=int64)
相关问题