Aman
Aman

Reputation: 47179

Get a Dictionary by applying function to pandas Series

I would like to apply a function to a dataframe and receive a single dictionary as a result. pandas.apply gives me a Series of dicts, and so currently I have to combine keys from each. I'll use an example to illustrate.

I have a pandas dataframe like so.

In [20]: df
Out[20]:
          0  1
0  2.025745  a
1 -1.840914  b
2 -0.428811  c
3  0.718237  d
4  0.079593  e

I have some function that returns a dictionary. For this example I'm using a toy lambda function lambda x: {x: ord(x)} that returns a dictionary.

In [22]: what_i_get = df[1].apply(lambda x: {x: ord(x)})
In [23]: what_i_get
Out[23]:
0     {'a': 97}
1     {'b': 98}
2     {'c': 99}
3    {'d': 100}
4    {'e': 101}
Name: 1

apply() gives me a series of dictionaries, but what I want is a single dictionary.

I could create it with something like this:

In [41]: what_i_want = {}
In [42]: for elem in what_i_get:
   ....:    for k,v in elem.iteritems():
   ....:        what_i_want[k] = v
   ....:

In [43]: what_i_want
Out[43]: {'a': 97, 'b': 98, 'c': 99, 'd': 100, 'e': 101}

But it seems I should be able to get what I want more directly.

Upvotes: 2

Views: 2320

Answers (2)

BrenBarn
BrenBarn

Reputation: 251355

Instead of returning a dict from your function, just return the mapped value, then create one dict outside the mapping operation:

>>> d
   Stuff
0     a
1     b
2     c
3     d
>>> dict(zip(d.Stuff, d.Stuff.map(ord)))
{'a': 97, 'b': 98, 'c': 99, 'd': 100}

Upvotes: 4

pydsigner
pydsigner

Reputation: 2885

Cutting out the items() middle-man:

what_i_want = {}
for elem in what_i_get:
    what_i_want.update(elem)

Upvotes: 1

Related Questions