对Pandas MultiIndex(多重索引)详解
创建多重索引
In[16]:df=pd.DataFrame(np.random.randn(3,8),index=['A','B','C'],columns=index) In[17]:df Out[17]: firstbarbazfooqux\ secondonetwoonetwoonetwoone A0.8957170.805244-1.2064122.5656461.4312561.340309-1.170299 B0.4108350.8138500.132003-0.827317-0.076467-1.1876781.130127 C-1.4136811.6079201.0241800.5696050.875906-2.2113720.974466 first secondtwo A-0.226169 B-1.436737 C-2.006747
获得索引信息
get_level_values
In[23]:index.get_level_values(0) Out[23]:Index(['bar','bar','baz','baz','foo','foo','qux','qux'],dtype='object',name='first') In[24]:index.get_level_values('second') Out[24]:Index(['one','two','one','two','one','two','one','two'],dtype='object',name='second')
基本索引
In[25]:df['bar'] Out[25]: secondonetwo A0.8957170.805244 B0.4108350.813850 C-1.4136811.607920 In[26]:df['bar','one'] Out[26]: A0.895717 B0.410835 C-1.413681 Name:(bar,one),dtype:float64 In[27]:df['bar']['one'] Out[27]: A0.895717 B0.410835 C-1.413681 Name:one,dtype:float64
使用reindex对齐数据
数据准备
In[11]:s=pd.Series(np.random.randn(8),index=arrays) In[12]:s Out[12]: barone-0.861849 two-2.104569 bazone-0.494929 two1.071804 fooone0.721555 two-0.706771 quxone-1.039575 two0.271860 dtype:float64
s序列加(0~-2)索引的值,因为s[:-2]没有最后两个的索引,所以为NaN.s[::2]意思是步长为1.
In[34]:s+s[:-2] Out[34]: barone-1.723698 two-4.209138 bazone-0.989859 two2.143608 fooone1.443110 two-1.413542 quxoneNaN twoNaN dtype:float64 In[35]:s+s[::2] Out[35]: barone-1.723698 twoNaN bazone-0.989859 twoNaN fooone1.443110 twoNaN quxone-2.079150 twoNaN dtype:float64
以上这篇对PandasMultiIndex(多重索引)详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。