简体   繁体   English

通过从另一个数据帧中查找来替换 Pandas 数据帧中的所有值

[英]Replace all values in pandas dataframe by lookup from another dataframe

Given the following data:鉴于以下数据:

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

which looks as:看起来像:

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

I would like to replace elements within it using the following:我想使用以下内容替换其中的元素:

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

resulting in the following data:产生以下数据:

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

The following works, but I feel there's a better approach:以下工作,但我觉得有一个更好的方法:

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

You could use DataFrame.replace passing the Series with index "from" and values "to" from reps :你可以使用DataFrame.replace传递Series与指数“从”和值“改为”从reps

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

[out] [出去]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据另一个 dataframe 中的查找值替换 pandas dataframe 值? - How to replace pandas dataframe values based on lookup values in another dataframe? 使用另一个 Dataframe 作为查找表替换 Pandas Dataframe 中的值 - Replace values in Pandas Dataframe using another Dataframe as a lookup table 使用Pandas将数据框中的值替换为另一个数据框 - Replace values in dataframe from another dataframe with Pandas 使用另一个DataFrame中的行的值查找并替换pandas.Dataframe中的列标题 - Lookup and replace column headings in a pandas.Dataframe with the values from rows in another DataFrame 替换 pandas dataframe 中的值 - Replace values in a pandas dataframe from another 如何用字典中的查找值替换 pandas DataFrame 列? - How to replace a pandas DataFrame column with lookup values from a dictionary? 从另一个DataFrame替换pandas.DataFrame中的值的优雅方法 - Elegant way to replace values in pandas.DataFrame from another DataFrame 如何用另一个 DataFrame 的值替换 pandas DataFrame? - How to replace pandas DataFrame with the values of another DataFrame? 如何用另一个 dataframe 替换 pandas dataframe 中的值 - How to replace values in pandas dataframe with another dataframe PANDAS - 如何根据另一个 dataframe 中的查找表替换 dataframe 中的值 - PANDAS - How do I replace the values in a dataframe based on a lookup table in another dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM