Answers:
In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict()
Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
速度比较(使用Wouter方法)
In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB'))
In [7]: %timeit dict(zip(df.A,df.B))
1000 loops, best of 3: 1.27 ms per loop
In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict()
1000 loops, best of 3: 987 us per loop
izip
而不是zip
; 实现;发电机会改变我的猜测
我找到了解决问题的更快方法,至少在使用以下方法的大型数据集上:
df.set_index(KEY).to_dict()[VALUE]
50,000行的证明:
df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)
%timeit dict(zip(df.A,df.B))
%timeit pd.Series(df.A.values,index=df.B).to_dict()
%timeit df.set_index('A').to_dict()['B']
输出:
100 loops, best of 3: 7.04 ms per loop # WouterOvermeire
100 loops, best of 3: 9.83 ms per loop # Jeff
100 loops, best of 3: 4.28 ms per loop # Kikohs (me)
在Python 3.6中,最快的方法仍然是WouterOvermeire。Kikohs的提议比其他两个方案要慢。
import timeit
setup = '''
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)
'''
timeit.Timer('dict(zip(df.A,df.B))', setup=setup).repeat(7,500)
timeit.Timer('pd.Series(df.A.values,index=df.B).to_dict()', setup=setup).repeat(7,500)
timeit.Timer('df.set_index("A").to_dict()["B"]', setup=setup).repeat(7,500)
结果:
1.1214002349999777 s # WouterOvermeire
1.1922008498571748 s # Jeff
1.7034366211428602 s # Kikohs
>>> import pandas as pd
>>> df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']})
>>> dict(sorted(df.values.tolist())) # Sort of sorted...
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> from collections import OrderedDict
>>> OrderedDict(df.values.tolist())
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])
解决方案说明: dict(sorted(df.values.tolist()))
鉴于:
df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']})
[出]:
Letter Position
0 a 1
1 b 2
2 c 3
3 d 4
4 e 5
尝试:
# Get the values out to a 2-D numpy array,
df.values
[出]:
array([['a', 1],
['b', 2],
['c', 3],
['d', 4],
['e', 5]], dtype=object)
然后(可选):
# Dump it into a list so that you can sort it using `sorted()`
sorted(df.values.tolist()) # Sort by key
要么:
# Sort by value:
from operator import itemgetter
sorted(df.values.tolist(), key=itemgetter(1))
[出]:
[['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]]
最后,将2个元素的列表转换成字典。
dict(sorted(df.values.tolist()))
[出]:
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
回答@sbradbio评论:
如果一个特定的键有多个值,而您想保留所有值,那么这不是最有效,但最直观的方法是:
from collections import defaultdict
import pandas as pd
multivalue_dict = defaultdict(list)
df = pd.DataFrame({'Position':[1,2,4,4,4], 'Letter':['a', 'b', 'd', 'e', 'f']})
for idx,row in df.iterrows():
multivalue_dict[row['Position']].append(row['Letter'])
[出]:
>>> print(multivalue_dict)
defaultdict(list, {1: ['a'], 2: ['b'], 4: ['d', 'e', 'f']})
{'key': [value1, value2]}