【问题标题】:How to create a loop and new data set from the function I created?如何从我创建的函数创建循环和新数据集?
【发布时间】:2019-01-21 17:48:20
【问题描述】:

我有这个房地产数据:

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

提前谢谢你。

【问题讨论】:

    标签: python pandas function loops dataframe


    【解决方案1】:

    通常使用数据帧,如果可以的话,最好避免显式循环,并使用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()])
    

    【讨论】:

      猜你喜欢
      • 2020-10-31
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-17
      • 2018-04-12
      相关资源
      最近更新 更多