使用字典重新映射 pandas 列中的值,保留 NaN [英] Remap values in pandas column with a dict, preserve NaNs

查看:27
本文介绍了使用字典重新映射 pandas 列中的值,保留 NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本看起来像这样的字典:di = {1: "A", 2: "B"}

我想将其应用于类似于以下内容的数据框的col1"列:

 col1 col20 瓦1 1 22 2 南

获得:

 col1 col20 瓦1 一个 22 B NaN

我怎样才能最好地做到这一点?出于某种原因,与此相关的谷歌搜索术语仅向我显示了有关如何从 dicts 制作列的链接,反之亦然:-/

解决方案

您可以使用 .replace.例如:

<预><代码>>>>df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}})>>>di = {1:A",2:B"}>>>df列 1 列 20 瓦1 1 22 2 南>>>df.replace({"col1": di})列 1 列 20 瓦1 一个 22 B NaN

或直接在系列,即df["col1"].replace(di, inplace=True).

I have a dictionary which looks like this: di = {1: "A", 2: "B"}

I would like to apply it to the "col1" column of a dataframe similar to:

     col1   col2
0       w      a
1       1      2
2       2    NaN

to get:

     col1   col2
0       w      a
1       A      2
2       B    NaN

How can I best do this? For some reason googling terms relating to this only shows me links about how to make columns from dicts and vice-versa :-/

解决方案

You can use .replace. For example:

>>> df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}})
>>> di = {1: "A", 2: "B"}
>>> df
  col1 col2
0    w    a
1    1    2
2    2  NaN
>>> df.replace({"col1": di})
  col1 col2
0    w    a
1    A    2
2    B  NaN

or directly on the Series, i.e. df["col1"].replace(di, inplace=True).

这篇关于使用字典重新映射 pandas 列中的值,保留 NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆