Python 按多列分组Period()键错误

Python 按多列分组Period()键错误,python,pandas,Python,Pandas,从多列组中获取pandas组时遇到了一些问题,我猜我遗漏了一些小的内容,希望如此。下面是一个将演示问题的测试用例: import pandas as pd import numpy as np df2 = pd.DataFrame({ 'date' : [pd.Timestamp('2016-12-1'), pd.Timestamp('2016-12-1'),pd.Timestamp('2016-11-1'),pd.Timestamp('2016-11

从多列组中获取pandas组时遇到了一些问题,我猜我遗漏了一些小的内容,希望如此。下面是一个将演示问题的测试用例:

import pandas as pd
import numpy as np
df2 = pd.DataFrame({ 
                     'date' : [pd.Timestamp('2016-12-1'), pd.Timestamp('2016-12-1'),pd.Timestamp('2016-11-1'),pd.Timestamp('2016-11-1')],
                     'number' : np.array(list(range(4)),dtype='int32'),
                     'category' : pd.Categorical(["test","other","test","other"]),
                     'this' : 'foo' })

print(df2)

        category       date  number this
    0     test 2016-12-01       0  foo
    1    other 2016-12-01       1  foo
    2     test 2016-11-01       2  foo
    3    other 2016-11-01       3  foo

df2['period'] = df2.date.dt.to_period("M")

print(df2)

      category       date  number this  period
    0     test 2016-12-01       0  foo 2016-12
    1    other 2016-12-01       1  foo 2016-12
    2     test 2016-11-01       2  foo 2016-11
    3    other 2016-11-01       3  foo 2016-11

grouped1 = df2.groupby(['period'])

print(grouped1.groups)
    {Period('2016-12', 'M'): [0, 1], Period('2016-11', 'M'): [2, 3]}

print(grouped1.get_group(pd.Period('2016-12', 'M')))
      category       date  number this  period
    0     test 2016-12-01       0  foo 2016-12
    1    other 2016-12-01       1  foo 2016-12

grouped2 = df2.groupby(['period', 'category'])

print(grouped2.groups)
    {(Period('2016-11', 'M'), 'test'): [2], (Period('2016-11', 'M'), 'other'): [3], (Period('2016-12', 'M'), 'other'): [1], (Period('2016-12', 'M'), 'test'): [0]}

print(grouped2.get_group((pd.Period('2016-11', 'M'), 'test')))
      Traceback (most recent call last):
      .....
      File "C:/Users/XXXX/XXXX/testcase.py", line 32, in <module>
print(grouped2.get_group((pd.Period('2016-11', 'M'), 'test')))

      File "F:\Python\WinPython-32bit-3.4.4.1\python-3.4.4\lib\site-packages\pandas\core\groupby.py", line 648, in get_group
raise KeyError(name)

    KeyError: (Period('2016-11', 'M'), 'test')
这显然很有效


是否有某种棘手的方法可以让
Period()
对象“可命名”?还是我完全遗漏了什么?

我无法重现这个错误。我把你的代码直接运行了一遍。尝试将组转换为列表,并在该列表的第一个元素上使用get_groups
a=list(grouped2.groups)
然后
grouped2.get_group(a[0])
I在pandas 0.18中重现错误,而不是在pandas 0.19中重现错误。你能升级吗?升级清除了它,以备参考,以防它对其他人有帮助。我在0.17.1上使用过。非常感谢。
grouped2 = df2.groupby(['this', 'category'])

print(grouped2.groups)

print(grouped2.get_group(('foo', 'test')))