![](/img/trans.png)
[英]pandas assign value to more than one columns based on a condition using more than 20 columns
[英]Identifying and removing outliers based on more than one condition in a dataset using Python
我正在為回歸建模准備一個數據集。 我想在這樣做之前刪除所有異常值。 該數據集有 7 個本質上是連續的變量。 其中五個變量可以普遍解決。 但是,首先需要在男性和女性參與者之間划分兩個變量,這兩個變量是身高和體重。 顯然這兩個測量值在男性和女性之間會有所不同,因此為了獲取異常值,我需要區分男性和女性的數據,然后評估/刪除每個人的身高和體重的異常值,然后將這些數據與我的數據合並已經准備好了。 有沒有一種簡單的方法可以做到這一點? 到目前為止,我一直在相鄰的 5 個變量上使用四分位數范圍,這些變量不需要除以男性和女性,對每個變量使用這個代碼......
Q1 = df["Variable"].quantile(0.25)
Q3 = df["Variable"].quantile(0.75)
IQR = Q3-Q1
Lower_Fence = Q1 - (1.5*IQR)
Upper_Fence = Q3 + (1.5*IQR)
print(Lower_Fence)
print(Upper_Fence)
df[((df["Variable"] < Lower_Fence) | (df["Variable"] > Upper_Fence))] # Detection of outliers
df[~((df["Variable"] < Lower_Fence) | (df["Variable"] > Upper_Fence))]` # Removal of outliers
我對 python 比較陌生。
您可以為您的“異常值”邏輯定義 function,然后將其重復應用於所有列,無論是否使用 groupby:
def is_outlier(s, quantiles=[.25, .75], thresholds=[-.5, .5]):
# change the thresholds to [-1.5, 1.5] to reflect IQR as per your question
a, b = s.quantile(quantiles)
iqr = b - a
lo, hi = np.array(thresholds) * iqr + [a, b]
return (s < lo) | (s > hi)
簡單測試:
n = 20
np.random.seed(0)
df = pd.DataFrame(dict(
status=np.random.choice(['dead', 'alive'], n),
gender=np.random.choice(['M', 'F'], n),
weight=np.random.normal(150, 40, n),
diastolic=np.random.normal(80, 10, n),
cholesterol=np.random.normal(200, 20, n),
))
示例用法:
mask = is_outlier(df['diastolic']) # overall outliers
# or
mask = df.groupby('gender')['weight'].apply(is_outlier) # per gender group
過濾數據的用法:
mask = False
# overall outliers
for k in ['diastolic', 'cholesterol']: # etc
mask |= is_outlier(df[k])
# per-gender outliers
gb = df.groupby('gender')
for k in ['weight']: # and any other columns needed for per-gender
mask |= gb[k].apply(is_outlier)
# finally, select the non-outliers
df_filtered = df.loc[~mask]
順便說一句,請注意每個性別的異常值與整體有何不同,例如“體重”:
df.groupby('gender')['weight'].apply(is_outlier) == is_outlier(df['weight'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.