我知道我的问题有different种变体。但我希望我的某些方面有所不同,并且不会被标记。使用Python 2.7,Pandas,Dictionaries。我有一个数据框,非常类似于以下内容:
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()并不好。它需要是一个正常的词典。这有什么解决方案吗? 或者我应该放弃使用熊猫?
答案 0 :(得分:0)
词典本质上是无序的。因此,这两本词典是等价的。您可能需要考虑OrderedDict
模块中的collections
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'}
哪个不关心订单。