【问题标题】:apply function to Pandas dataframe with index as argument将函数应用于以索引为参数的 Pandas 数据帧
【发布时间】:2020-09-28 22:47:27
【问题描述】:

我创建了一个接受一个参数的函数,但现在我想将它应用到以索引为参数的整个数据帧中。我的第一个冲动是做一个 for 循环,但我知道这些在 Pandas 中是不受欢迎的。

我有一些来自世界银行 API 的数据,在一个数据框“df”中适用于许多国家和年份:

+-------------------------------------------------------------+
|                             ODA  gdp_per_cap   sant    mort |
| country     date                                            |
| Afghanistan 2010 6235319824.219       11.264 34.177  87.600 |
|             2009 6113120117.188       18.515 32.910  91.400 |
|             2008 4811209960.938        1.594 31.655  95.400 |
|             2007 4982609863.281       11.023 30.412  99.500 |
|             2006 2895830078.125        2.253 29.181 103.700 |
+-------------------------------------------------------------+

国家和日期是索引。我需要创建一个新的数据框并用计算填充它。新数据框具有相同的国家/地区索引,但没有日期。

我写了这个函数来计算一些字段:

def fill_df(country):
    total_oda = bil(df.loc[country, 'ODA'].sum()/10)
    gdp = df.loc[country, 'gdp_per_cap'].mean()
    sanitation = percent_change(country, 'sant')
    mortality = percent_change(country, 'mort')
    metric = (-pow(total_oda, .5) + gdp/4 + sanitation*.5 - mortality*0.5 + 80)*.2
    final_df.loc[country] = [total_oda, gdp, sanitation, mortality, metric]

fill_df('Afghanistan')
fill_df('Burundi')

好的,因此该功能一次适用于一个国家/地区。这是新的 final_df:

+-------------------------------------------------------------+
|                             ODA   gdp   sant    mort metric |
| country                                                     |
| Afghanistan               3.329 6.606 45.293 -29.695 23.464 |
| Burundi                   0.392 0.236  1.115 -39.439 19.942 |
| Burkina Faso                NaN   NaN    NaN     NaN    NaN |
| Central African Republic    NaN   NaN    NaN     NaN    NaN |
| Congo, Dem. Rep.            NaN   NaN    NaN     NaN    NaN |
| Eritrea                     NaN   NaN    NaN     NaN    NaN |
+-------------------------------------------------------------+

现在我想将它应用于所有 final_df。下面是这个想法,但不起作用,因为我的函数采用一个参数而不是值索引。

country_idx = df.index.get_level_values(0).unique()
final_df.apply(fill_df, axis=0, args=country_idx)

如何将函数应用到final_df?

【问题讨论】:

  • 使用groupby(country),将您的聚合功能应用于每个组不是更容易吗?您可以将df 设为fill_df 的参数(这也消除了df 作为代码中的全局变量)。然后只需将fill_df 应用于每个组:df.groupby('country').apply(lambda gr: fill_df(gr))

标签: python-3.x pandas dataframe


【解决方案1】:

您可以在 level=0 参数上使用 groupbyagg

final_df = df.groupby(level=0).agg((
              total_oda = ('ODA', lambda x: x.sum()/10),
              gdp = ('gdp_per_cap', 'mean'),
              sanitation = ('sant', percent_change),
              mortality = ('mort', percent_change),
              metric = (-pow(total_oda, .5) + gdp/4 + sanitation*.5 - mortality*0.5 + 80)*.2
))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 2020-05-11
    • 1970-01-01
    相关资源
    最近更新 更多