从词典中选择值以创建新的DataFrame列

时间:2015-03-05 19:54:22

标签: python pandas dictionary dataframe

我有一本字典

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并遍历每一行,还是有更有效的替代方案?

1 个答案:

答案 0 :(得分:5)

您可以在此处使用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可以使用字典,系列或函数,并返回带有映射值的新系列。它也非常有效地实现(例如,比apply更多)。

相关问题