使用字典查找更新熊猫列

时间:2019-02-12 14:18:38

标签: pandas

具有数据帧df:

import pandas as pd
import numpy as np

i = ['dog', 'cat', 'rabbit', 'elephant'] * 3

df = pd.DataFrame(np.random.randn(12, 2), index=i, columns=list('AB'))

...以及B列的查询字典:

b_dict = {'elephant': 2.0, 'dog': 5.0}

如何将df的B列替换为大象和狗行?

df['B'].update(b_dict)给出:

  

AttributeError:“ dict”对象没有属性“ reindex_like”

3 个答案:

答案 0 :(得分:3)

转换为pd.Seriesupdate可以正常工作

df['B'].update(pd.Series(b_dict))
df
Out[185]: 
                 A         B
dog      -1.340695  5.000000
cat      -0.196993 -0.021518
rabbit   -0.274504 -0.260294
elephant -0.170860  2.000000
dog      -0.432042  5.000000
cat       0.868669  0.204100
rabbit    0.435023 -1.968735
elephant -0.668397  2.000000
dog       0.706603  5.000000
cat       0.158067  0.675130
rabbit    0.429419  0.374914
elephant  1.559330  2.000000

答案 1 :(得分:2)

使用np.where()仅在条件匹配时替换并保留其余部分:

df['B']=np.where(df.index.isin(b_dict.keys()),df.index.map(b_dict),df.B)

答案 2 :(得分:0)

您可以使用np.select

cond = [(df.index == x) for x in b_dict.keys()]
vals = b_dict.values()

df['B'] = np.select(cond, vals)

Out[13]:         A    B
dog       0.523732  5.0
cat      -0.923483  0.0
rabbit    0.339749  0.0
elephant  1.204516  2.0
dog       1.799287  5.0
cat       0.214085  0.0
rabbit   -1.685739  0.0
elephant -0.475113  2.0
dog       1.381671  5.0
cat       1.343616  0.0
rabbit    0.627273  0.0
elephant  0.630255  2.0