Select 字典中的值以创建新的 DataFrame 列

Select values from dictionary to create a new DataFrame column

我有字典

type_dict = {3: 'foo', 4: 'bar',5: 'foobar', 6: 'foobarbar'}

和一个包含以下列的 DataFrame:

>>> df.type
0     3
1     4
2     5
3     6
4     3
5     4
6     5
7     6
8     3

我想创建一个包含相应 type_dict 值的新列,但以下是我唯一能想到但没有用的东西:

>>> type_dict[df.type]
TypeError: 'Series' objects are mutable, thus they cannot be hashed

>>> type_dict[df.type.values]
TypeError: unhashable type: 'numpy.ndarray'

我真的需要 apply 并遍历每一行,还是有更有效的替代方法?

您可以在此处使用 map

>>> df['type'].map(type_dict)
0          foo
1          bar
2       foobar
3    foobarbar
4          foo
5          bar
6       foobar
7    foobarbar
8          foo
Name: type, dtype: object

map 可以采用字典、系列或函数,以及 return 具有映射值的新系列。它的实施也非常有效(例如,比 apply 高得多)。