首页 > 解决方案 > 如何通过函数传递数据帧并返回另一个数据帧?

问题描述

我有一个数据框,其中包含有关社区、房产类型、谈判类型和价格的房地产信息。它看起来像这样:

**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

感谢您提前提供任何帮助。

标签: pythonpandasfunctiondataframe

解决方案


您的代码中有一些错误:

  1. 使用pd.DataFrame构造函数构造一个新的数据框。
  2. 作为二维对象,您应该将列表列表提供给构造函数。注意双开和闭方括号。
  3. 对于数据帧的长度,使用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')

推荐阅读