我有一个这样的字典: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

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


当前回答

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

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

其他回答

DSM有一个公认的答案,但编码似乎并不适用于每个人。下面是一个适用于当前版本的熊猫(截至2018年8月的0.23.4):

import pandas as pd

df = pd.DataFrame({'col1': [1, 2, 2, 3, 1],
            'col2': ['negative', 'positive', 'neutral', 'neutral', 'positive']})

conversion_dict = {'negative': -1, 'neutral': 0, 'positive': 1}
df['converted_column'] = df['col2'].replace(conversion_dict)

print(df.head())

你会看到它是这样的:

   col1      col2  converted_column
0     1  negative                -1
1     2  positive                 1
2     2   neutral                 0
3     3   neutral                 0
4     1  positive                 1

pandas.DataFrame.replace的文档在这里。

更本土的熊猫方法是应用替换函数,如下所示:

def multiple_replace(dict, text):
  # Create a regular expression  from the dictionary keys
  regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))

  # For each match, look-up corresponding value in dictionary
  return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text) 

一旦定义了函数,就可以将其应用到数据框架中。

di = {1: "A", 2: "B"}
df['col1'] = df.apply(lambda row: multiple_replace(di, row['col1']), axis=1)

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

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

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

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快得多。这种方法有两个版本,这取决于你的字典是否穷尽地映射了所有可能的值(以及你是否希望不匹配的值保留它们的值或被转换为nan):

详尽的映射

在本例中,表单非常简单:

df['col1'].map(di)       # note: if the dictionary does not exhaustively map all
                         # entries then non-matched entries are changed to NaNs

尽管map通常以函数作为参数,但它也可以以字典或系列作为参数

简单的映射

如果你有一个非穷尽映射,并且希望保留现有的不匹配的变量,你可以添加fillna:

df['col1'].map(di).fillna(df['col1'])

正如@jpp在这里的回答:通过字典有效地替换pandas系列中的值

基准

在pandas 0.23.1版本中使用以下数据:

di = {1: "A", 2: "B", 3: "C", 4: "D", 5: "E", 6: "F", 7: "G", 8: "H" }
df = pd.DataFrame({ 'col1': np.random.choice( range(1,9), 100000 ) })

使用%timeit进行测试时,map似乎比replace快大约10倍。

请注意,使用map的加速将随着数据的不同而不同。最大的加速似乎是使用大字典和详尽的替换。参见@jpp的回答(上面有链接),了解更广泛的基准测试和讨论。