python - 如何从我创建的函数创建循环和新数据集?

标签 python pandas function loops dataframe

我有这个房地产数据:

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 提供的优化方法。在您的情况下,您可以通过将 groupbydescribe 结合使用来消除循环,将您想要的百分位数传递给参数 percentiles。然后,只需选择所需的列并适本地重命名它们:

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()])

关于python - 如何从我创建的函数创建循环和新数据集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51848724/

相关文章:

python - Pandas Groupby 绘制按顶级分组的多重索引

python - 如何在 Sphinx 运行时预处理源文件?

python - 解析日期列后 pandas 合并功能出现问题

python - 如何将列表列表中的所有字符串转换为整数?

python - Pandas:在列的应用函数中使用索引值

python - 使用每组至少一个具有非缺失 cusip 标识符的记录来过滤所有重复观察

bash - 如何从函数中有效地中止 Bash 脚本的执行

java - 从 JSP 页面调用 servlet 上的函数

arrays - 为什么这个函数句柄在不正确的上下文中使用?

python - 捕获静态 'file not found' 错误