从使用大 pandas 系列的字典中选择 [英] Select from dictionary using pandas series
本文介绍了从使用大 pandas 系列的字典中选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一本字典
type_dict = {3: 'foo', 4:'bar',5:'foobar', 6:'foobarbar'}
和一个包含以下列的数据框:
and a data frame 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'
我真的需要申请
并且遍历每一行,还是有更有效的替代方法?
Do I really need to apply
and iterate through each row, or is there a more efficient alternative?
推荐答案
您可以使用 map
here: / p>
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
可以使用字典,系列或函数,并返回带有映射值的新系列。它也非常有效地实现(例如比应用
更多)。
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).
这篇关于从使用大 pandas 系列的字典中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文