根据字典替换整个数据框中的值

Replacing values in entire dataframe based on dictionary

我有一个大型数据框,我想根据字典更改其中的每个值。目前我正在使用一个循环:

for column in df.columns:
     df = df.replace({column: dictionary})

这可行,但速度很慢。这个单个 for 循环占用了我整个代码 运行 所需时间的大约 90%。有使用 loc、map 或 replace 的更快方法吗?

已经有很多其他类似的问题,但似乎几乎每个人都只是试图更改个别列而不是整个数据框。

我在 Windows 上使用带有 Python 3.9 的 Spyder。谢谢!

编辑:我找到了一种通过切换行和列来加快速度的方法。以前我有很多列和很少的行,现在它是另一种方式,代码要快得多。不过,有没有办法替换整个数据框中的值,而不仅仅是个别列?

Is there a way to replace values in the entire dataframe rather than just individual columns?

使用:

df = df.replace(dictionary)