2

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

我有一个像这样的熊猫数据框。

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 x: {x: ord(x)}返回字典的玩具 lambda 函数。

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}

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

4

2 回答 2

4

而不是从你的函数返回一个字典,只返回映射的值,然后在映射操作之外创建一个字典:

>>> 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}
于 2012-11-06T20:42:26.217 回答
1

去掉 items() 中间人:

what_i_want = {}
for elem in what_i_get:
    what_i_want.update(elem)
于 2012-11-06T20:41:40.710 回答