组织以下pandas Dataframe的最有效方法是什么:
data =
Position Letter
1 a
2 b
3 c
4 d
5 e
进入像alphabet[1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e']
这样的字典?
答案 0 :(得分:113)
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
答案 1 :(得分:45)
我发现了一种解决问题的更快方法,至少在实际大型数据集上使用:
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)
答案 2 :(得分:1)
在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
答案 3 :(得分:1)
>>> 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']})