从字典中选择值以创建新的DataFrame列 [英] Select values from dictionary to create a new DataFrame column

查看:558
本文介绍了从字典中选择值以创建新的DataFrame列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字典

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

和带有以下列的DataFrame:

and a DataFrame with the following column:

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

我想创建一个包含相应的type_dict值的新列,但是以下是我唯一想到的并且无法正常工作的情况:

I want to create a new column containing the corresponding type_dict value, but the following was the only thing I could come up and was not working:

>>> 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并遍历每一行,还是有更有效的选择?

Do I really need to apply and iterate through each row, or is there a more efficient alternative?

推荐答案

您可以使用 map 此处:

You could use map here:

>>> 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要多得多).

map can take a dictionary, Series or function and return a new Series with the mapped values. It is also very efficiently implemented (much more so than apply, for example).

这篇关于从字典中选择值以创建新的DataFrame列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆