【问题标题】:Pandas Dataframe Column Manipulation and conversion to DictionaryPandas Dataframe 列操作和转换为字典
【发布时间】:2018-01-01 04:21:56
【问题描述】:

我知道我的问题有different 的变体。但我希望我的在某些方面有所不同,并且不会被标记。使用 Python 2.7、熊猫、字典。我有一个数据框,非常类似于以下内容:

boxNumber     Content
[1.0, 2.0]     A
[2.0, 4.5]     B
[2.5, 3.0]     C
[1.5, 2.5]     F
[1.4, 4.5]     D
[1.3, 3.2]     E

现在我必须获得像 {A:B, C:F, D:E} 这样的字典。我通过以下方式解决这个问题。我已将其转换为 pandas 数据框,删除了所有空值行。

keys = ['A', 'B', 'C', 'F','D', 'E']

test1 = df[df.Content.str.match('A').shift(1).fillna(False)]
test2 = df[df.Content.str.match('C').shift(1).fillna(False)]
test3 = df[df.Content.str.match('D').shift(1).fillna(False)]
values = [test1.Content.iloc[0], test2.Content.iloc[0],test3.Content.iloc[0] 
item1 = dict(zip(keys, values))
print(item1)

我的输出是

{'A':'B', 'D':'E', 'C':'F'}

但我需要

{'A':'B', 'C':'F', 'D':'E'}

由于 dict 在 python 2.7 中是无序的,我的最终输出也变得无序! OrderedDict() 不好。它需要是一个正常的字典。有什么解决办法吗? 还是我应该放弃使用 Pandas?

【问题讨论】:

  • 我不明白问题出在哪里。 {'A':'B', 'C':'F', 'D':'E'} == {'A':'B', 'D':'E', 'C':'F'} 为什么需要订购?
  • 因为 'A', 'B', 'C', 'D', 'E', 'F' 都是从 PDF 中提取的 json ......这些都是例子......A可以是姓名,B 可以是姓氏...然后是“年龄”的 D...E 是 #age...

标签: python python-2.7 pandas dictionary dataframe


【解决方案1】:

字典本质上是无序的。因此,这两个字典是等价的。您可能需要考虑collections 模块中的OrderedDict

from collections import OrderedDict

OrderedDict(zip(df.Content.iloc[::2], df.Content.iloc[1::2]))

OrderedDict([(u'A', u'B'), (u'C', u'F'), (u'D', u'E')])

它的行为类似于字典,但保持顺序。

相对于:

dict(zip(df.Content.iloc[::2], df.Content.iloc[1::2]))

{u'A': u'B', u'C': u'F', u'D': u'E'}

不关心顺序。

【讨论】:

  • 除了OrderedDict()没有别的办法了吗?
  • 我最终阅读了有关词典的更多信息,这似乎是要走的路...谢谢
猜你喜欢
  • 2014-01-05
  • 2021-11-28
  • 1970-01-01
  • 2021-12-01
  • 2017-12-26
  • 2014-12-30
相关资源
最近更新 更多