如何将阈值应用于pandas数据帧列并在阈值之外输出行?

2024-09-26 18:06:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有大量的产品系列数据集。我试图捕捉任何奇怪的数据条目,它们的价格比其他家庭成员高/低。例如,我有一个thispandas.DataFrame

df =
Prices    Product Family
0    1.99        Yoplait
1    1.89        Yoplait
2    1.59        Yoplait
3    1.99        Yoplait
4    7.99        Yoplait
5    12.99       Hunts 
6    12.99       Hunts 
7    2.99        Hunts 
8    12.49       Hunts

我想写一个for循环,它遍历每个产品系列,设置某种阈值来标识哪些产品有问题(第4行和第7行),然后输出该行。我该怎么做?在

到目前为止,我有这个:

^{pr2}$

然后,对于每个产品系列,我最好在for循环中完成if语句。有没有人对如何设置这个阈值并完成代码有什么想法(或者更好的主意)?在


Tags: 数据dataframedffor产品条目阈值product
3条回答

我想我的方法和斯蒂芬·劳赫的方法相似,唯一的区别是我标准化/规范化了每个组的prices。在

# Standardize or normalize the `Prices` per `ProductFamily` (absolute value)
df_std = df.groupby('ProductFamily').transform(lambda x: np.abs((x - x.mean()) / x.std()))

# We assume that any Price beyond one standard deviation is an outlier
outlier_mask = df_std['Prices'] > 1.0

# Split clean and outlier dataframes
df_clean = df[~outlier_mask]
df_outlier = df[outlier_mask]

使用pandas时,如果可能,最好不要使用循环。在您的例子中,我们可以使用groupby()来执行相似家族的操作。以下是一种通过使用不同于组中值的值来查找异常值的方法:

代码:

df['median'] = df.groupby('Product_Family').transform('median')
df['outlier'] = ((df.Prices - df['median']) / df['median']).abs() > 0.5

测试代码:

^{pr2}$

结果:

   Prices Product_Family  median  outlier
4    7.99        Yoplait    1.99     True
7    2.99          Hunts   12.74     True

   Prices Product_Family  median  outlier
0    1.99        Yoplait    1.99    False
1    1.89        Yoplait    1.99    False
2    1.59        Yoplait    1.99    False
3    1.99        Yoplait    1.99    False
4    7.99        Yoplait    1.99     True
5   12.99          Hunts   12.74    False
6   12.99          Hunts   12.74    False
7    2.99          Hunts   12.74     True
8   12.49          Hunts   12.74    False

我们也可以使用分位数进行离群点检测,并与其他答案一样进行分组和转换。以下使用0.05和0.95分位数作为限值:

# FIND LOWER AND UPPER LIMITS: 
df["lower"] = df.groupby("ProductFamily").transform(lambda x: x.quantile(0.05))
df["upper"] = df.iloc[:,0:2].groupby("ProductFamily").transform(lambda x: x.quantile(0.95))
print(df) 

# SELECT ROWS THAT MEET CRITERIA: 
df = df[(df.Prices > df.lower) & (df.Prices < df.upper)]
print(df)

# TO KEEP ORIGINAL 2 COLUMNS:
df = df.iloc[:,0:2]
print(df)

输出:

^{pr2}$

相关问题 更多 >

    热门问题