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

2024/10/6 14:30:29

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.

Select from dictionary using pandas series

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[df.type]

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

type_dict[df.type.values]

TypeError: unhashable type: 'numpy.ndarray'

Updated question:

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    carplt.scatter(df.meters, df.Speed, marker = df.type.map(mkr_dict)) 

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

Answer

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

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

https://en.xdnf.cn/q/70360.html

Related Q&A

Django No Module Named URLs error

There are many similar questions posted already, but Ive already tried those solutions to no avail. Im working through a basic Django tutorial, and here is my code:urls.pyfrom django.conf.urls import …

Matplotlib artist to stay same size when zoomed in but ALSO move with panning?

This is a very direct follow-up on this question.Using matplotlib, Id like to be able to place a sort of "highlighting bar" over a range of data markers that I know will all be in a straight …

How to invoke Lambda function with Event Invocation Type via API Gateway?

Docs says:By default, the Invoke API assumes RequestResponse invocation type. You can optionally request asynchronous execution by specifying Event as the InvocationType. So all I can send to my functi…

How do I unlock the app engine database when localhost runs?

Right now I get a blank page when localhost runs, but the deployed app is fine. The logs show the "database is locked". How do I "unlock" the database for localhost?

PyCrypto: Generate RSA key protected with DES3 password

I have been able to create a RSA key protected by password with DES3 (well... I think because Im very new to this encryption world) by using the command:openssl genrsa -out "/tmp/myKey.pem" -…

Normalize/Standardize a numpy recarray

I wonder what the best way of normalizing/standardizing a numpy recarray is. To make it clear, Im not talking about a mathematical matrix, but a record array that also has e.g. textual columns (such as…

How to read /dev/log?

I would like to directly access to syslog messages from Python by reading /dev/log.My (very limited) understanding is that the correct way is to read from there is to bind a datagram socket. import soc…

Determining if a number evenly divides by 25, Python

Im trying to check if each number in a list is evenly divisible by 25 using Python. Im not sure what is the right process. I want to do something like this:n = [100, 101, 102, 125, 355, 275, 435, 134, …

OpenCV SimpleBlobDetector detect() call throws cv2.error: Unknown C++ exception from OpenCV code?

I need to detect semicircles on image and I find follow stuff for this: import cv2 import numpy as npdef get_circle(img_path):im = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)detector = cv2.SimpleBlobDet…

Is it possible to add a global argument for all subcommands in Click based interfaces?

I am using Click under a virtualenv and use the entry_point directive in setuptools to map the root to a function called dispatch.My tool exposes two subcommands serve and config, I am using an option …