2017-09-16 142 views

回答

0

在对某些分类变量上的数据框进行子分类时,有序索引与loc一起使用。例如,对于以下的数据帧

import pandas as pd 
index = ['a', 'b', 'c', 'a', 'b', 'c'] 
x = np.arange(6) 
df = pd.DataFrame({"x": x}, 
        index = pd.Categorical(index, categories=['a', 'b', 'c'], ordered=True)) 

df.loc['b':'c']给出错误,而

df = df.sort_index() 
df.loc['b':'c'] 

给出正确地选择行。

x 
b 1 
b 4 
c 2 
c 5