![](/img/trans.png)
[英]How to replace pandas dataframe values based on lookup values in another dataframe?
[英]Replace all values in pandas dataframe by lookup from another dataframe
鉴于以下数据:
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))
你可以使用DataFrame.replace
传递Series
与指数“从”和值“改为”从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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.