微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python:如何从pandas系列中获取字典中的值

我是python的新手,并试图从字典中获取值,其中键在数据帧列(pandas)中定义.我搜索了很多,最接近的是a
在下面的链接中的问题,但它没有答案.

所以,在这里,我试图找到相同类型的问题的答案.

Select from dictionary using pandas series

我有一本字典

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’对象是可变的,因此它们不能被散列

type_dict[df.type.values]

TypeError:不可用类型:’numpy.ndarray

更新的问题:

对于pandas DataFrame,比如’df’,我如何用米型作为标记词典的关键来绘制速度超过米.

mkr_dict = {'gps': 'x', 'phone': '+', 'car': 'o'}

x = {'speed': [10, 15, 20, 18, 19], 'meters' : [122, 150, 190, 230, 300], 'type': ['phone', 'phone', 'gps', 'gps', 'car']}

df = pd.DataFrame(x)
   meters  speed   type
0     122     10  phone
1     150     15  phone
2     190     20    gps
3     230     18    gps
4     300     19    car

plt.scatter(df.meters, df.Speed, marker = df.type.map(mkr_dict)) 

散点图对我不起作用……

解决方法:

将dict作为arg传递给map

In [79]:

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

这将查找dict中的键值并从dict返回相关值.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐