TypeError:不支持的操作数类型 - :' str'和' str'熊猫Groupby

时间:2014-08-07 20:33:31

标签: python pandas

我遇到了使用pandas groupby object的类型问题。

    #define a dataframe
    df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar','foo', 'bar', 'foo', 'foo'],\
               'B' : ['one', 'one', 'two', 'three',\
                       'two', 'two', 'one', 'three'],\
                'C' : randn(8), 'D' : randn(8)})

    print df


    #define a function applied to chunks of Groupedby Object
    def compute_displacement(df):
        return df.diff(periods=1)

    #If I apply this function onto groupby object like this
    grouped=df.groupby(['A','B'])['C','D']
    hi=grouped.apply(compute_displacement)

我会得到这样的错误:

    TypeError: unsupported operand type(s) for -: 'str' and 'str'

我的想法是索引中只有字符串,即列A和列B,它们是否应该不参与compute_displacement函数的计算?我该如何解决这个问题

解决。这是版本问题,在版本0.12中发生,但在版本0.14中不存在

1 个答案:

答案 0 :(得分:1)

当访问pandas中的多个列时,您需要使用双括号,如下所示。

grouped=df.groupby(['A','B'])[['C','D']]