2016-08-22 89 views
1

我有一个DF执行算术对字典

product currency price 
    a  USD  2 
    b  AUD  3 
    c  GBP  9 
    .... 

被引用,我有一个字典:

cc={"USD": 1, "AUD":.75, "GBP: 1.13} 

我想改价乘以价格乘以CC字典中对应货币的价值,所以我尝试过:

df.price.apply(lambda x: x*cc[df['currency']]) 

其中给出错误

TypeError: 'Series' objects are mutable, thus they cannot be hashed 

谢谢!

回答

2

您可以使用地图(确保在该系列的所有值也都在字典):

df['currency'].map(cc) * df['price'] 
Out: 
0  2.00 
1  2.25 
2 10.17 
dtype: float64 

如果要更改价格列,分配回:

df['price'] = df['currency'].map(cc) * df['price'] 
0
df = pd.DataFrame([['a', 'USD', 2L], 
        ['b', 'AUD', 3L], 
        ['c', 'GBP', 9L]], 
        columns=['product', 'currency', 'price']) 

cc = pd.Series({"USD": 1, "AUD":.75, "GBP": 1.13}) 

df.price *= cc.ix[df.currency].values 

df 

enter image description here