【问题标题】:access the outer element of tuple in pandas dataframe groupby object访问 pandas 数据框 groupby 对象中元组的外部元素
【发布时间】:2016-02-04 03:22:43
【问题描述】:

我在多索引数据框(例如 (a,b))上创建了一个 groupby 对象。我可以使用df.get_group((a,b)) 访问内部组。但是,我也希望能够访问外部组,例如df.get_group((a,))。我可以通过df.xs(key,level) 命令间接实现这一点,但这不是解决问题的理想方法。有人可以帮我解决这个问题吗?

    df1.get_group(('specialty finance','mortgage finance'))
                                          lasts         prev ticker
industry          sub_industry                                     
specialty finance mortgage finance   190.000000   190.649994   dewh
                  mortgage finance   252.699997   253.350006   grhf
                  mortgage finance  1179.800049  1180.050049   hdfc
                  mortgage finance   693.849976   708.450012   ihfl
                  mortgage finance   450.950012   468.250000  lichf

df1.get_group(('specialty finance',))
ValueError: must supply a a same-length tuple to get_group with multiple grouping keys

【问题讨论】:

  • 内组和外组是什么意思?
  • 我将元组对称为内部组和外部组。在示例 df1.get_group(('specialty finance','mortgage finance')) 中,'specialty finance' 是外部组,''mortgage finance' 是内部组。一个外部组可以有很多子组,我可以像上面那样访问子组,但是我如何访问外部组(它将列出所有子组(内部组))。我希望我说得通,示例代码清楚地显示了我想要实现的目标。

标签: python pandas


【解决方案1】:

这取决于您的第一个 groupby() 确定 get_group() 命名对象。如果您仅按行业(外部组)在原始多索引数据帧上运行 groupby,则可以单独输出到“专业金融”组:

df1 = originaldf.groupby(['industry']).get_group('specialty finance')

或者,您可以通过 groupby 对象的所有元素继续当前分组和 iterate,甚至根据您的特定行业进行分组:

dfgrp = originaldf.groupby(['industry','sub_industry'])

for industry, sub_industry in dfgrp:
    if 'specialty finance' in industry:
        print(industry)
        print(sub_industry)

【讨论】:

    猜你喜欢
    • 2021-09-14
    • 2014-06-10
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 2019-09-30
    相关资源
    最近更新 更多