python - 如何通过函数传递数据帧并返回另一个数据帧?
问题描述
我有一个数据框,其中包含有关社区、房产类型、谈判类型和价格的房地产信息。它看起来像这样:
**neighborhood type_property type_negotiation price**
Smallville house rent 2000
Oakville apartment for sale 100000
King Bay house for sale 250000
.
.
我想要做的是通过一个函数传递这个函数,该函数按我输入的社区对数据框进行排序,如果它是一所房子,如果它要出售,符合这些要求的房产数量,还给出第 90 个百分位数和第 10 个百分位数百分位。
到目前为止我的函数和代码如下,但我一直遇到多种语法和其他错误:
def function(string):
a = df[(df.type_negotiation == 'for sale')&(df.type_property == 'house')&(df.neighborhood == string)
b = pd.new_df([a.price.quantile(.10),a.price.quantile(.90),a.shape], columns=('tenthpercentile','ninetiethpercentile','Quantity'))
return b
感谢您提前提供任何帮助。
解决方案
您的代码中有一些错误:
- 使用
pd.DataFrame
构造函数构造一个新的数据框。 - 作为二维对象,您应该将列表列表提供给构造函数。注意双开和闭方括号。
- 对于数据帧的长度,使用
len(a)
orlen(a.index)
或a.shape[0]
。a.shape
返回一个大小为 2 的元组,表示行数和列数。顺便说一句,这与(2)中的要求非常吻合。
最后,您将获得一个单行数据框:
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
一个更惯用和通用的解决方案,包括您的数据框作为您的函数的输入参数并利用pd.DataFrame.pipe
:
def foo(df, string):
# as before
df.pipe(foo, 'KingBay')
推荐阅读
- laravel - 流明名媛授权流程
- android - 创建自定义等候室
- c# - 我可以在 asp mvc core 2.0 中添加第四个路由令牌吗?
- c# - 泛型构造要求类型“Cell<'T>”是非托管类型
- c# - 调用抛出 InvalidOperationException
- python-3.x - 在 django2 中,如何分别为新对象和旧对象设置不同的默认值?
- d3.js - 传单底图上的静态 svg。d3 js json的投影
- python - 无法从 django 管理面板创建新帖子,但它是从 python shell 创建的
- javascript - 如何在网页上显示来自 Twitter 的标签计数
- r - bookdown中章节标题和文本的奇怪拉伸