1

在这个例程的最后一条语句中,我得到一个 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:只能与其他分层索引对象一起调用

我怎样才能克服这个错误,所以我可以正确地将每个州的商品数量乘以相应的价格?

4

1 回答 1

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
于 2012-12-18T03:04:50.860 回答