通过将函数应用于pandas Series来获取字典

时间:2012-11-06 20:36:45

标签: python pandas

我想将函数应用于数据帧并作为结果接收单个字典。 pandas.apply给了我一系列的dicts,所以目前我必须组合各自的键。我将用一个例子来说明。

我有一个像这样的pandas数据帧。

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

我有一些返回字典的函数。对于这个例子,我使用了一个返回字典的玩具lambda函数lambda x: {x: ord(x)}

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()给了我一系列字典,但我想要的是一本字典。

我可以用这样的东西创建它:

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}

但似乎我应该能够更直接地得到我想要的东西。

2 个答案:

答案 0 :(得分:4)

不是从函数返回一个dict,只需返回映射值,然后在映射操作之外创建一个dict:

>>> 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}

答案 1 :(得分:1)

切断项目()中间人:

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