繁体   English   中英

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

[英]Python: how to get values from a dictionary from pandas series

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

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

使用pandas系列从字典中选择

我有一本字典

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返回相关值。

在熊猫中,这应该有效

df['val'] = df.apply(lambda x: type_dict[x['type']], axis=1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM