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

标签 python pandas

我想将一个函数应用于数据帧并接收一个字典作为结果。 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/

相关文章:

Python AWS SQS 与 MOTO 模拟

python - 将两个 numpy 数组与连续行合并

python - Tensorflow dynamic_rnn 弃用

python - Pandas 数据透视表到 One_hot

Python Pandas,将 groupby() 组标签设置为新数据框中的索引

python - 如何在python中左连接2个数据帧,如果过滤后第二个数据帧中有多个匹配行,则与第一行连接

python - 在 Pandas Python 中组合两个数据框

python - 如何将 Pandas 数据框转换为命名元组

python - 在 Ubuntu/Quckly 中为命令行服务器提供基本 GUI 的一般布局和架构?

python - 通过多个主机的pexpect ssh