Python 仅选择多索引数据帧的一个索引
我正在尝试从多索引数据帧中仅使用一个索引来创建新的数据帧Python 仅选择多索引数据帧的一个索引,python,pandas,select,dataframe,indexing,Python,Pandas,Select,Dataframe,Indexing,我正在尝试从多索引数据帧中仅使用一个索引来创建新的数据帧 A B C first second bar one 0.895717 0.410835 -1.413681 two 0.805244 0.813850 1.607920 baz one -1.206412 0.132003 1.024180 tw
A B C
first second
bar one 0.895717 0.410835 -1.413681
two 0.805244 0.813850 1.607920
baz one -1.206412 0.132003 1.024180
two 2.565646 -0.827317 0.569605
foo one 1.431256 -0.076467 0.875906
two 1.340309 -1.187678 -2.211372
qux one -1.170299 1.130127 0.974466
two -0.226169 -1.436737 -2.006747
理想情况下,我想要这样的东西:
In: df.ix[level="first"]
以及:
基本上,我想删除除level
first
之外的多索引的所有其他索引。有一种简单的方法可以做到这一点吗?一种方法可以是简单地将df.index
重新绑定到所需的多索引级别。可以通过指定要保留的标签名称来执行此操作:
df.index = df.index.get_level_values('first')
或者使用级别的整数值:
df.index = df.index.get_level_values(0)
多索引的所有其他级别都将在此处消失。解决方案是相当新的,并将函数用作
In [88]: df.xs('bar', level='first')
Out[88]:
Second Third
one A -2.315312
B 0.497769
C 0.108523
two A -0.778303
B -1.555389
C -2.625022
dtype: float64
也可以使用多个索引,如
In [89]: df.xs(('bar', 'A'), level=('First', 'Third'))
Out[89]:
Second
one -2.315312
two -0.778303
dtype: float64
下面是示例的设置
import pandas as pd
import numpy as np
arrays = [
np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])
]
index = pd.MultiIndex.from_tuples(list(zip(*arrays)), names=['first', 'second'])
df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)
df.index.names = pd.core.indexes.frozen.FrozenList(['First', 'Second', 'Third'])
df = df.unstack()
我使用get_level_值(0)来获取多索引组中的第一级索引,从而构建一个包含聚合值和编码值的描述字典值的数据帧。我通过以下方式获得组中“airline_enc”值的索引
def getAirlineByGrouped(grouped,dictGeneric):
mylist=[]
for key in grouped.index.get_level_values(0):
item=dictGeneric.get(key)
mylist.append(item)
return mylist
encoder=LabelEncoder()
df['airline_enc']=encoder.fit_transform(df['airline'])
dictAirline= df[['airline_enc','airline']].set_index('airline_enc').to_dict()
grouped=results.groupby(['airline_enc','rating'])['recommended'].count()
#print(grouped)
airlines=getAirlineByGrouped(grouped, dictAirline['airline'])
result_df=pd.DataFrame({'index': grouped.index.get_level_values(0),'value':grouped.values,'airline':airlines})
result_df.plot(x='airline',y='value')
plt.xticks(rotation=90)
def getAirlineByGrouped(grouped,dictGeneric):
mylist=[]
for key in grouped.index.get_level_values(0):
item=dictGeneric.get(key)
mylist.append(item)
return mylist
encoder=LabelEncoder()
df['airline_enc']=encoder.fit_transform(df['airline'])
dictAirline= df[['airline_enc','airline']].set_index('airline_enc').to_dict()
grouped=results.groupby(['airline_enc','rating'])['recommended'].count()
#print(grouped)
airlines=getAirlineByGrouped(grouped, dictAirline['airline'])
result_df=pd.DataFrame({'index': grouped.index.get_level_values(0),'value':grouped.values,'airline':airlines})
result_df.plot(x='airline',y='value')
plt.xticks(rotation=90)