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

Python 从字典中选择值以创建新的DataFrame列,python,pandas,dictionary,dataframe,Python,Pandas,Dictionary,Dataframe,我有一本字典 type_dict = {3: 'foo', 4: 'bar',5: 'foobar', 6: 'foobarbar'} 以及具有以下列的数据帧: >>> 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_dict = {3: 'foo', 4: 'bar',5: 'foobar', 6: 'foobarbar'}
以及具有以下列的数据帧:

>>> 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高很多。

您可以在这里使用:

映射可以获取字典、序列或函数,并返回带有映射值的新序列。例如,它的实现效率也比apply高得多。

在将数据类型从对象切换到整数后,这一点很有效。在将数据类型从对象切换到整数后,这一点很有效。
>>> 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