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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30312566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:22:03  来源:igfitidea点击:

Python: how to get values from a dictionary from pandas series

pythondictionarypandaskeydataframe

提问by Kexin Xu

I am very new to python and trying to get value from dictionary where keys are defined in a dataframe column (pandas). I searched quite a bit and the closest thing is a question in the link below, but it doesnt come with an answer.

我对 python 非常陌生,并试图从字典中获取值,其中键在数据框列(pandas)中定义。我搜索了很多,最接近的是下面链接中的一个问题,但它没有给出答案。

So, here I am trying to find answer for the same type of question.

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

Select from dictionary using pandas series

使用Pandas系列从字典中选择

I have a dictionary

我有字典

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

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 值的新列,但以下是我唯一能想到的并且不起作用:

type_dict[df.type]

TypeError: 'Series' objects are mutable, thus they cannot be hashed

类型错误:“系列”对象是可变的,因此它们不能被散列

type_dict[df.type.values]

TypeError: unhashable type: 'numpy.ndarray'

类型错误:不可散列的类型:'numpy.ndarray'

Updated question:

更新的问题:

for pandas DataFrame, say 'df', how can i plot speed over meters with type as the key of marker dictionary.

对于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)) 

the scatter plot doesn't work for me...

散点图对我不起作用...

回答by EdChum

Pass the dict as an arg to map:

将 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

This will lookup the key value in the dict and return the associated value from the dict.

这将在字典中查找键值并从字典中返回关联的值。

回答by Julien Spronck

In pandas, this should work

在Pandas中,这应该有效

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