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

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


当前回答

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

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)

其他回答

一个很好的完整的解决方案,保持你的类标签的映射:

labels = features['col1'].unique()
labels_dict = dict(zip(labels, range(len(labels))))
features = features.replace({"col1": labels_dict})

这样,您可以在任何时候引用labels_dict中的原始类标签。

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

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

鉴于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

或者适用:

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
>>> 

作为Nico Coallier(应用于多个列)和U10-Forward(使用apply风格的方法)提出的扩展,并将其总结为一行程序,我建议:

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

transform()将每一列作为一个系列处理。与.apply()相反,它传递在DataFrame中聚合的列。

因此,您可以应用Series方法map()。

最后,我发现了这个行为多亏了U10,你可以在.get()表达式中使用整个系列。除非我误解了它的行为,它按顺序处理系列而不是按位处理。 .get(x,x)表示映射字典中没有提到的值,否则.map()方法会将这些值视为Nan