在矩阵运算期间忽略层次索引

时间:2012-12-18 01:01:44

标签: python pandas

在这个例程的最后一个语句中,我得到一个TypeError

data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Missouri'],
        'year': [2000, 2001, 2002, 2001, 2002],
        'items': [5, 12, 6, 45, 0]}
frame = DataFrame(data)

def summary_pivot(df, row=['state'],column=['year'],value=['items'],func=len):
    return df.pivot_table(value, rows=row,cols=column,
                   margins=True, aggfunc=func, fill_value=0)

test = summary_pivot(frame)

In [545]: test
Out[545]: 
          items                 
year       2000  2001  2002  All
state                           
Missouri      0     0     1    1
Nevada        0     1     0    1
Ohio          1     1     1    3
All           1     2     2    5


price = DataFrame(index=['Missouri', 'Ohio'], columns = ['price'], data = [200, 250])

In [546]: price
Out[546]: 
          price
Missouri    200
Ohio        250

test * price

TypeError:只能与其他分层索引对象一起调用

如何通过此错误,以便我可以正确地将每个州的商品数量乘以相应的价格?

1 个答案:

答案 0 :(得分:0)

In [659]: price = Series(index = ['Missouri', 'Ohio'], data = [200, 250])

In [660]: test1 = test.items

In [661]: test1.mul(price, axis='index')
Out[661]: 
year      2000  2001  2002  All
All        NaN   NaN   NaN  NaN
Missouri     0     0   200  200
Nevada     NaN   NaN   NaN  NaN
Ohio       250   250   250  750