我想将一个函数应用于数据帧并接收一个字典作为结果。 pandas.apply 给了我一系列字典,所以目前我必须组合每个字典的键。我用一个例子来说明。
我有一个像这样的 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}
但看来我应该能够更直接地得到我想要的东西。
最佳答案
不要从函数中返回字典,只需返回映射值,然后在映射操作之外创建一个字典:
>>> 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}
关于python - 通过将函数应用于 pandas Series 来获取字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13258974/