我有一个这样的字典:di = {1: " a ", 2: "B"}

我想把它应用到一个类似于数据框架的col1列:

     col1   col2
0       w      a
1       1      2
2       2    NaN

得到:

     col1   col2
0       w      a
1       A      2
2       B    NaN

我怎样才能做到最好呢?出于某种原因,谷歌与此相关的术语只向我展示了如何从字典中制作列,反之亦然:-/


当前回答

你可以使用。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
  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

或直接在级数上,即df["col1"]。替换(di,原地= True)。

其他回答

或者适用:

df['col1'].apply(lambda x: {1: "A", 2: "B"}.get(x,x))

演示:

>>> df['col1']=df['col1'].apply(lambda x: {1: "A", 2: "B"}.get(x,x))
>>> df
  col1 col2
0    w    a
1    1    2
2    2  NaN
>>> 

如果你在一个数据框架中有多个列需要重新映射,那么这个问题就更严重了:

def remap(data,dict_labels):
    """
    This function take in a dictionnary of labels : dict_labels 
    and replace the values (previously labelencode) into the string.

    ex: dict_labels = {{'col1':{1:'A',2:'B'}}

    """
    for field,values in dict_labels.items():
        print("I am remapping %s"%field)
        data.replace({field:values},inplace=True)
    print("DONE")

    return data

希望对别人有用。

干杯

鉴于map比replace快(@JohnE的解决方案),在打算将特定值映射到NaN的非穷举映射时需要小心。在这种情况下,正确的方法要求在使用.fillna时屏蔽Series,否则将撤消到NaN的映射。

import pandas as pd
import numpy as np

d = {'m': 'Male', 'f': 'Female', 'missing': np.NaN}
df = pd.DataFrame({'gender': ['m', 'f', 'missing', 'Male', 'U']})

keep_nan = [k for k,v in d.items() if pd.isnull(v)]
s = df['gender']

df['mapped'] = s.map(d).fillna(s.mask(s.isin(keep_nan)))

    gender  mapped
0        m    Male
1        f  Female
2  missing     NaN
3     Male    Male
4        U       U

你可以使用。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
  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

或直接在级数上,即df["col1"]。替换(di,原地= True)。

你可以用数据帧中缺失的对来更新你的映射字典。例如:

df = pd.DataFrame({'col1': ['a', 'b', 'c', 'd', np.nan]})
map_ = {'a': 'A', 'b': 'B', 'd': np.nan}

# Get mapping from df
uniques = df['col1'].unique()
map_new = dict(zip(uniques, uniques))
# {'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd', nan: nan}

# Update mapping
map_new.update(map_)
# {'a': 'A', 'b': 'B', 'c': 'c', 'd': nan, nan: nan}

df['col2'] = df['col1'].map(dct_map_new)

结果:

  col1 col2
0    a    A
1    b    B
2    c    c
3    d  NaN
4  NaN  NaN