通过从另一个数据框中查找替换熊猫数据框中的所有值

时间:2020-03-07 02:52:12

标签: python pandas replace

给出以下数据:

df = pd.DataFrame(
    dict(
        x1=["zero", "one", "two"],
        x2=["one", "zero", "zero"],
        x3=["zero", "two", "one"],
        x4=["zero", "two", "two"],
    )
)

其外观为:

In [2]: df
Out[2]:
     x1    x2    x3    x4
0  zero   one  zero  zero
1   one  zero   two   two
2   two  zero   one   two

我想使用以下内容替换其中的元素:

reps = pd.DataFrame(
    dict(
        val_from=["zero", "one", "two"],
        val_to=["nothing", "single", "couple"],
    )
)

得出以下数据:

    x1    : x2     : x3     : x4
  single  : single : single : single
   single : single : couple : couple
   couple : single : single : couple

以下方法可行,但我认为有更好的方法:

replacement = {x:y for x,y in zip(reps['val_from'], reps['val_to'])}
df.transform(lambda x: x.replace(replacement))

1 个答案:

答案 0 :(得分:1)

您可以使用DataFrame.replace,将Series与索引{from“和值” to“传递自reps

df.replace(reps.set_index(['val_from'])['val_to'])

[出]

        x1       x2       x3       x4
0  nothing   single  nothing  nothing
1   single  nothing   couple   couple
2   couple  nothing   single   couple