【问题标题】:How to groupby a dictionary and aggregate a pandas dataframe [duplicate]如何按字典分组并聚合熊猫数据框[重复]
【发布时间】:2020-08-21 14:08:57
【问题描述】:

我有一个索引为“国家”的数据框“df”和一个“估计人口”列。

该索引有 15 个国家/地区名称。 我还有一本字典:

ContinentDict  = {'China':'Asia', 
              'United States':'North America', 
              'Japan':'Asia', 
              'United Kingdom':'Europe', 
              'Russian Federation':'Europe', 
              'Canada':'North America', 
              'Germany':'Europe', 
              'India':'Asia',
              'France':'Europe', 
              'South Korea':'Asia', 
              'Italy':'Europe', 
              'Spain':'Europe', 
              'Iran':'Asia',
              'Australia':'Australia', 
              'Brazil':'South America'}

字典中的所有国家都存在于数据框中。 使用给定的字典,我需要“按大陆对国家进行分组,然后创建一个显示每个国家/地区估计人口的平均值和标准偏差的日期框。”

这是我试过的代码:

df2=df.groupby(ContinentDict)['Estimated Population'].agg({'mean':np.mean,'std':np.std})

当我运行此代码时,我收到错误“没有要聚合的数字类型”

然后我尝试了以下代码:

df2=pd.to_numeric(df.groupby(ContinentDict)['Estimated Population']).agg({'mean':np.mean,'std':np.std})

这给了我错误“缓冲区的维数错误(预期为 1,得到 2)”

如何消除这些错误并获得我需要的数据库?

【问题讨论】:

  • 包含您的数据框示例。
  • @ShubhamSharma 我编辑了它现在有数据框图片的问题。
  • Estimated Population列的dtype是什么,可以通过df["Estimated Population"].dtype查看。
  • @Harsha 您需要根据硬编码而不是图片添加示例数据框。
  • @ShubhamSharma "dtype('O')"

标签: python pandas


【解决方案1】:

在应用.agg 函数之前,您需要更改Estimated Population 列的dtype

用途:

df['Estimated Population'] = df['Estimated Population'].astype(float)

或者,

df['Estimated Population'] = pd.to_numeric(df['Estimated Population'])

【讨论】:

    猜你喜欢
    • 2019-03-17
    • 2019-08-02
    • 1970-01-01
    • 2021-07-28
    • 2022-01-21
    • 1970-01-01
    • 2021-01-05
    • 2020-12-01
    • 2018-11-04
    相关资源
    最近更新 更多