我有这个房地产数据:
neighborhood type_property type_negotiation price
Smallville house rent 2000
Oakville apartment for sale 100000
King Bay house for sale 250000
...
我创建了一个函数,通过您输入的邻域对这个大数据集进行排序,如果它是一个待售房屋,然后返回这些房屋的第10和第90百分位数和数量.我在下面有这个:
def foo(string):
a = df[(df.type_negotiation == 'forsale')&(df.type_property == 'house')&(df.neighborhood == string)]
b = pd.DataFrame([[a.price.quantile(0.1), a.price.quantile(0.9), len(a.index)]],
columns=('tenthpercentile', 'ninetiethpercentile', 'Quantity'))
return b
print(foo('KingBay'))
tenthpercentile ninetiethpercentile Quantity
0 250000.0 250000.0 1
我想编写一个循环来为我所拥有的邻域列表执行此操作,然后在一个帧中编译新数据中的每个返回.看起来像这样:
tenthpercentile ninetiethpercentile Quantity
King Bay 250000.0 250000.0 1
Smallville 99000.0 120000.0 8
Oakville 45000.0 160000.0 6
先感谢您.
解决方法:
通常使用数据帧,如果可以,最好避免使用显式循环,并使用pandas提供的优化方法.在你的情况下,你可以通过使用groupby with describe
来消除循环,将你想要的百分位数传递给参数百分位数.然后,只需选择所需的列并适当地重命名它们:
new_df = (df.groupby('neighborhood')
.describe(percentiles=[0.1,0.9])
['price'][['10%','90%','count']]
.rename(columns={'count':'Quantity',
'10%':'tenthpercentile',
'90%':'ninetiethpercentile'}))
在你的情况下(因为每个社区只有一个例子):
>>> new_df
tenthpercentile ninetiethpercentile Quantity
neighborhood
King Bay 250000.0 250000.0 1.0
Oakville 100000.0 100000.0 1.0
Smallville 2000.0 2000.0 1.0
[编辑]:我刚看到你的功能,你只看(df.type_negotiation ==’for sale’)& (df.type_property ==’house’).为此,只需添加一个loc来按以下条件过滤数据帧:
new_df = (df.loc[(df.type_negotiation == 'for sale')
& (df.type_property == 'house')]
.groupby('neighborhood')
.describe(percentiles=[0.1,0.9])
['price'][['10%','90%','count']]
.rename(columns={'count':'Quantity',
'10%':'tenthpercentile',
'90%':'ninetiethpercentile'}))
另外,如果你使用你的函数和循环(不是我推荐它),你可以这样做:
pd.concat([foo(i) for i in df.neighborhood.unique()])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。