Python:如何从 pandas 系列的字典获取值 [英] Python: how to get values from a dictionary from pandas series
问题描述
我对python非常新鲜,并试图从数据框中定义键的字典中获取值(pandas)。我搜索了很多,最接近的是一个
问题在下面的链接,但它没有一个答案。
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.
所以,在这里,我试图找到同样类型的问题的答案。
So, here I am trying to find answer for the same type of question.
我有一个字典
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:'系列'对象是可变的,因此它们不能被哈希
TypeError: 'Series' objects are mutable, thus they cannot be hashed
type_dict[df.type.values]
TypeError :unhashable类型:'numpy.ndarray'
TypeError: unhashable type: 'numpy.ndarray'
更新问题:
为大熊猫DataFrame,说'df' ,我如何绘制速度超过米的类型作为标记字典的关键。
for pandas DataFrame, say 'df', how can i plot speed over meters with type as the key of marker dictionary.
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...
推荐答案
将dict作为参数传递给 map
:
Pass the dict as an arg to 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
这将查找口头和回报t他与dict相关联的价值。
This will lookup the key value in the dict and return the associated value from the dict.
这篇关于Python:如何从 pandas 系列的字典获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!