Pandas Group-by Multiple Columns Period()键错误

时间:2016-12-08 12:30:26

标签: 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-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_group调用时,它是用于分组的单个向量完全正常。但是当它是多列分组的一部分时,它会抛出name key error,因为无法找到Period()元组的get_group部分。

我猜是当对象pd.Period()处于多列get_group所需的元组形式时,它可能无法评估?

我已尝试使用Period()应评估的内容,例如2016-11,但仍会获得名称密钥错误。

抓住吸管我尝试stringify Period('2016-11', 'M')并将其设置为x = Period('2016-11', 'M'),但两者都无法在没有名称密钥错误的情况下运行。

作为一个完整性检查我试过:

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

print(grouped2.groups)

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

这显然工作正常。

我是否有某种棘手的方法可以使Period()个对象具有名称&#39 ;?还是有什么我完全不知道的?

0 个答案:

没有答案