use*_*734 101 python dictionary dataframe pandas
组织以下pandas Dataframe的最有效方法是什么:
data =
Position Letter
1 a
2 b
3 c
4 d
5 e
Run Code Online (Sandbox Code Playgroud)
进入一本字典alphabet[1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e']
?
Jef*_*eff 145
In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict()
Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
Run Code Online (Sandbox Code Playgroud)
速度比较(使用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
Run Code Online (Sandbox Code Playgroud)
Kik*_*ohs 59
我发现了一种解决问题的更快方法,至少在实际大型数据集上使用:
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']
Run Code Online (Sandbox Code Playgroud)
输出:
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)
Run Code Online (Sandbox Code Playgroud)
Bab*_*pha 30
dict(zip(data['Position'], data['Letter']))
Run Code Online (Sandbox Code Playgroud)
这会给你:
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
Run Code Online (Sandbox Code Playgroud)
在 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)
Run Code Online (Sandbox Code Playgroud)
结果:
1.1214002349999777 s # WouterOvermeire
1.1922008498571748 s # Jeff
1.7034366211428602 s # Kikohs
Run Code Online (Sandbox Code Playgroud)
>>> 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)])
Run Code Online (Sandbox Code Playgroud)
解释解决方案: dict(sorted(df.values.tolist()))
鉴于:
df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']})
Run Code Online (Sandbox Code Playgroud)
[出去]:
Letter Position
0 a 1
1 b 2
2 c 3
3 d 4
4 e 5
Run Code Online (Sandbox Code Playgroud)
尝试:
# Get the values out to a 2-D numpy array,
df.values
Run Code Online (Sandbox Code Playgroud)
[出去]:
array([['a', 1],
['b', 2],
['c', 3],
['d', 4],
['e', 5]], dtype=object)
Run Code Online (Sandbox Code Playgroud)
然后可选:
# Dump it into a list so that you can sort it using `sorted()`
sorted(df.values.tolist()) # Sort by key
Run Code Online (Sandbox Code Playgroud)
或者:
# Sort by value:
from operator import itemgetter
sorted(df.values.tolist(), key=itemgetter(1))
Run Code Online (Sandbox Code Playgroud)
[出去]:
[['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]]
Run Code Online (Sandbox Code Playgroud)
最后,将 2 个元素的列表转换为 dict。
dict(sorted(df.values.tolist()))
Run Code Online (Sandbox Code Playgroud)
[出去]:
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
Run Code Online (Sandbox Code Playgroud)
回答@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'])
Run Code Online (Sandbox Code Playgroud)
[出去]:
>>> print(multivalue_dict)
defaultdict(list, {1: ['a'], 2: ['b'], 4: ['d', 'e', 'f']})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
73789 次 |
最近记录: |