cs9*_*s95 3 python multi-index dataframe pandas
给出两个数组:
x
[('010_628', '2543677'), ('010_228', '2543677'), ('015_634', '2543677')]
y
array([['me', 10228955],
['me', 10228955],
['me', 10228955]], dtype=object)
Run Code Online (Sandbox Code Playgroud)
目前,这段代码为我提供了一个具有平坦元组索引的数据帧:
df = pd.DataFrame(x, index=y, columns=['pm_code', 'sec_pm'])
df
pm_code sec_pm
(me, 10228955) 010_628 2543677
(me, 10228955) 010_228 2543677
(me, 10228955) 015_634 2543677
Run Code Online (Sandbox Code Playgroud)
我怎样才能创建一个MultiIndex看起来像这样的数据框?
pm_code sec_pm
state site_no
me 10228955 010_628 2543677
010_228 2543677
015_634 2543677
Run Code Online (Sandbox Code Playgroud)
我尝试过使用pd.MultiIndex.from_tuples但是我无法做到这一点.谢谢您的帮助.
附录:性能比较
# unutbu #1
%timeit pd.DataFrame(x, index=pd.MultiIndex.from_arrays(y.T), columns=['pm_code', 'sec_pm'])
1000 loops, best of 3: 1.25 ms per loop
# unutbu #2
%timeit pd.DataFrame(x, index=pd.MultiIndex.from_tuples(y.tolist()), columns=['pm_code', 'sec_pm'])
1000 loops, best of 3: 1.47 ms per loop
# piRSquared
%timeit pd.DataFrame(x, index=y.T.tolist(), columns=['pm_code', 'sec_pm'])
1000 loops, best of 3: 1.41 ms per loop
# Andrew L
%timeit pd.DataFrame(x, index=[y[:,0], y[:,1]], columns=['pm_code', 'sec_pm'])
1000 loops, best of 3: 1.29 ms per loop
Run Code Online (Sandbox Code Playgroud)
x2 = np.repeat(x, 10000, 0)
y2 = np.repeat(x, 10000, 0)
# unutbu #1
%timeit pd.DataFrame(x2, index=pd.MultiIndex.from_arrays(y2.T), columns=['pm_code', 'sec_pm'])
100 loops, best of 3: 17.3 ms per loop
# unutbu #2
%timeit pd.DataFrame(x2, index=pd.MultiIndex.from_tuples(y2.tolist()), columns=['pm_code', 'sec_pm'])
10 loops, best of 3: 30.5 ms per loop
# piRSquared
%timeit pd.DataFrame(x2, index=y2.T.tolist(), columns=['pm_code', 'sec_pm'])
10 loops, best of 3: 37.2 ms per loop
# Andrew L
%timeit pd.DataFrame(x2, index=[y2[:,0], y2[:,1]], columns=['pm_code', 'sec_pm'])
100 loops, best of 3: 22 ms per loop
Run Code Online (Sandbox Code Playgroud)
来自这个问题的数据.
你可以使用pd.MultiIndex.from_arrays(y.T):
In [53]: pd.DataFrame(x, index=pd.MultiIndex.from_arrays(y.T), columns=['pm_code', 'sec_pm'])
Out[53]:
pm_code sec_pm
me 10228955 010_628 2543677
10228955 010_228 2543677
10228955 015_634 2543677
Run Code Online (Sandbox Code Playgroud)
或者pd.MultiIndex.from_tuples(y.tolist()):
In [54]: pd.DataFrame(x, index=pd.MultiIndex.from_tuples(y.tolist()), columns=['pm_code', 'sec_pm'])
Out[54]:
pm_code sec_pm
me 10228955 010_628 2543677
10228955 010_228 2543677
10228955 015_634 2543677
Run Code Online (Sandbox Code Playgroud)