[英]Remove values above threshold
我正在嘗試從數據框中刪除值,即溫度,一些值是 10.0、10.5、40.0,但我有一些像 140.0、159.5 那樣沒有意義的值,我想刪除它們。 我使用以下功能,但我沒有像索引那樣刪除任何東西
def remove_outlier(df, col_name):
threshold = 100.0 # Anything that occurs abovethan this will be removed.
value_counts = df.stack().value_counts() # Entire DataFrame
to_remove = value_counts[value_counts >= threshold].index
if(len(to_remove) > 0):
df[col_name].replace(to_remove, np.nan)
return df
嘗試
df = df[df[col_name] < threshold]
要么
df = df[~ df[col_name] > threshold]
擴展GRS 的答案
>>> import pandas as pd
>>> d
City Temperature
0 A 10.0
1 B 10.5
2 C 140.0
3 D 30.0
4 E 145.0
5 F 99.0
>>> def remove_outlier(dataFrame, col_name='Temperature', threshold=100):
... return dataFrame[dataFrame[col_name] < threshold]
>>> remove_outlier(d)
City Temperature
0 A 10.0
1 B 10.5
3 D 30.0
5 F 99.0
您還可以使用df.query
的功能pandas
與@
運算符來讀取變量的值:
df = df.query('col_name < @threshold')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.