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    car
plt.scatter(df.meters, df.Speed, marker = df.type.map(mkr_dict)) 
the scatter plot doesn't work for me...
to_dict() function is used to convert Series to Dictionary (dict) object. Use this method if you have a Series with a relevant index and want to convert it to a python dictionary (dict) object by converting indices of series as keys and the values of series as values.
In Python, you can get the value from a dictionary by specifying the key like dict[key] . In this case, KeyError is raised if the key does not exist. Note that it is no problem to specify a non-existent key if you want to add a new element.
Series as specialized dictionary In this way, you can think of a Pandas Series a bit like a specialization of a Python dictionary. A dictionary is a structure that maps arbitrary keys to a set of arbitrary values, and a Series is a structure which maps typed keys to a set of typed values.
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.
In pandas, this should work
df['val'] = df.apply(lambda x: type_dict[x['type']], axis=1)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With