我有房地产数据:
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
我想编写一个循环,对我拥有的邻域列表执行此操作,然后在一个新的dat a帧中编译每个返回。看起来像这样:
tenthpercentile ninetiethpercentile Quantity
King Bay 250000.0 250000.0 1
Smallville 99000.0 120000.0 8
Oakville 45000.0 160000.0 6
先谢谢你。你知道吗
通常对于数据帧,如果可以,最好避免显式循环,并使用} ,将所需的百分位数传递给参数
pandas
提供的优化方法。在您的例子中,您可以通过使用groupby
和^{percentiles
来消除循环。然后,只需选择所需的列并适当地重命名它们:在您的案例中(因为每个社区只有一个例子):
[编辑]:我刚刚看到在您的函数中,您只查看
(df.type_negotiation == 'for sale') & (df.type_property == 'house')
。为此,只需添加一个loc
即可根据以下条件过滤数据帧:另外,如果您想使用函数和循环(我不建议这样做),您可以:
相关问题 更多 >
编程相关推荐