迭代Groupby对象上的列

2024-09-26 18:00:16 发布

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

我创建了一个6列数据框来进行真实状态分析。以下列为:指数、租金、行政区、卧室编号、停车位和建筑面积。之后,我创建了一个groupby对象:

boroughs = df.groupby(by = "Borough")

正如所料,现在它有了自治区作为索引,还有4列。我想知道如何迭代这些列(可能使用for循环)。我的最终目标是为每一列概括以下异常值删除表达式:

Q1 = boroughs.quantile(0.25)
Q3 = boroughs.quantile(0.75)
IIQ = Q3 - Q1
inf_lim = Q1 - 1.5*IIQ
sup_lim = Q3 + 1.5*IIQ

rent = pd.DataFrame()
for borough in boroughs.groups.keys():
    which_borough = df["Borough"] == borough
    not_outlier = ((df["Rent_Price"] >= inf_lim[borough]) & (df["Rent_Price"] <= sup_lim[borough]))
    selection = which_borough & not_outlier
    df_selection = df[selection]
    aluguel = pd.concat([rent, df_selection])

df["Rent_Price"].describe()信息:

count        757.000000
mean        3943.546896
std        45374.384250
min            0.000000
25%          750.000000
50%         1200.000000
75%         1850.000000
max      1000000.000000

rent["Rent_Price"].describe()信息:

count      701.000000
mean      1478.723252
std       1651.573796
min          0.000000
25%        750.000000
50%       1200.000000
75%       1800.000000
max      35999.000000

正如你所看到的,经过这个过程后,平均值、标准差和最大值都显著降低,并且删除了56项


Tags: dfforpriceboroughgroupbyquantileq3selection
1条回答
网友
1楼 · 发布于 2024-09-26 18:00:16

试试这个:

for col in ['Rent_Price', 'borough', 'number_of_bedrooms', 'parking_spaces', 'floor_area']:
    ans=df[(df[col]<=(df[col].quantile(0.75)+(1.5*(df[col].quantile(0.75)-df[col].quantile(0.25))))) & (df[col]>=(df[col].quantile(0.25)-(1.5*(df[col].quantile(0.75)-df[col].quantile(0.25)))))][col].describe()
    print(f'{col} Summary')
    print(ans)

按行政区划分:

for b in set(df.borough):
    df1=df[df.borough==b]
    for col in ['rent price', 'borough', 'nº of bedrooms', 'parking spaces', 'floor area']:
        ans=df1[(df1[col]<=(df1[col].quantile(0.75)+(1.5*(df1[col].quantile(0.75)-df1[col].quantile(0.25))))) & (df1[col]>=(df1[col].quantile(0.25)-(1.5*(df1[col].quantile(0.75)-df1[col].quantile(0.25)))))][col].describe()
        print(f'{col} Summary')
        print(ans)

相关问题 更多 >

    热门问题