python中multiindex如何索引_python – MultiIndex DataFrames的Pandas HDFStore:如何有效地获取所有索引...
在Pandas中,有沒有辦法以表格格式有效地提取HDFStore中存在的所有MultiIndex索引?
我可以使用where =來有效地選擇(),但我想要所有索引,而不是所有列.我也可以選擇()使用iterator = True來保存RAM,但這仍然意味著從磁盤讀取幾乎所有的表,所以它仍然很慢.
我一直在store.root..table.*東西打獵,希望我能得到一個索引值列表.我是在正確的軌道上嗎?
計劃B將保留一個較短的MultiIndex DataFrame,它只包含每次附加主數據時附加的空DataFrame.我可以檢索它并使索引比主要索引便宜得多.雖然不太優雅.
解決方法:
創建一個多索引df
In [35]: df = DataFrame(randn(100000,3),columns=list('ABC'))
In [36]: df['one'] = 'foo'
In [37]: df['two'] = 'bar'
In [38]: df.ix[50000:,'two'] = 'bah'
In [40]: mi = df.set_index(['one','two'])
In [41]: mi
Out[41]:
MultiIndex: 100000 entries, (foo, bar) to (foo, bah)
Data columns (total 3 columns):
A 100000 non-null values
B 100000 non-null values
C 100000 non-null values
dtypes: float64(3)
將其存儲為表格
In [42]: store = pd.HDFStore('test.h5',mode='w')
In [43]: store.append('df',mi)
get_storer將返回存儲的對象(但不檢索數據)
In [44]: store.get_storer('df').levels
Out[44]: ['one', 'two']
In [2]: store
Out[2]:
File path: test.h5
/df frame_table (typ->appendable_multi,nrows->100000,ncols->5,indexers->[index],dc->[two,one])
索引級別創建為data_columns,這意味著您可以在選擇中使用它們
這是如何只選擇索引
In [48]: store.select('df',columns=['one'])
Out[48]:
MultiIndex: 100000 entries, (foo, bar) to (foo, bah)
Empty DataFrame
選擇單個列并將其作為mi-frame返回
In [49]: store.select('df',columns=['A'])
Out[49]:
MultiIndex: 100000 entries, (foo, bar) to (foo, bah)
Data columns (total 1 columns):
A 100000 non-null values
dtypes: float64(1)
要將單個列選擇為Series(也可以是索引,因為它們存儲為列).這將非常快.
In [2]: store.select_column('df','one')
Out[2]:
0 ? ? foo
1 ? ? foo
2 ? ? foo
3 ? ? foo
4 ? ? foo
5 ? ? foo
6 ? ? foo
7 ? ? foo
8 ? ? foo
9 ? ? foo
10 ? ?foo
11 ? ?foo
12 ? ?foo
13 ? ?foo
14 ? ?foo
...
99985 ? ?foo
99986 ? ?foo
99987 ? ?foo
99988 ? ?foo
99989 ? ?foo
99990 ? ?foo
99991 ? ?foo
99992 ? ?foo
99993 ? ?foo
99994 ? ?foo
99995 ? ?foo
99996 ? ?foo
99997 ? ?foo
99998 ? ?foo
99999 ? ?foo
Length: 100000, dtype: object
如果你真的想要最快的選擇只有索引
In [4]: %timeit store.select_column('df','one')
100 loops, best of 3: 8.71 ms per loop
In [5]: %timeit store.select('df',columns=['one'])
10 loops, best of 3: 43 ms per loop
或者獲得完整的索引
In [6]: def f():
...: level_1 = store.select_column('df','one')
...: level_2 = store.select_column('df','two')
...: return MultiIndex.from_arrays([ level_1, level_2 ])
...:
In [17]: %timeit f()
10 loops, best of 3: 28.1 ms per loop
如果你想要每個級別的值,這是一種非常快速的方法
In [2]: store.select_column('df','one').unique()
Out[2]: array(['foo'], dtype=object)
In [3]: store.select_column('df','two').unique()
Out[3]: array(['bar', 'bah'], dtype=object)
標簽:python,pandas,hdfstore
來源: https://codeday.me/bug/20190517/1121943.html
總結
以上是生活随笔為你收集整理的python中multiindex如何索引_python – MultiIndex DataFrames的Pandas HDFStore:如何有效地获取所有索引...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 易语言webservice接口_易语言语
- 下一篇: 期货配资是什么玩意