Python pandas multiindex选择值

时间:2018-02-12 09:56:34

标签: python-3.x pandas multi-index

我有一个大多数数值的pandas multiindex,但数据中也有一些None,NaN或“ - ”。像这样:

                0         1         2         3
bar one -0.096648 -0.080298  0.859359 -0.030288
    two       NaN -0.431791  1.923893 -1.544845
    thr -0.358526  1.416211  1.589617  0.284130
baz one  0.639951 -0.008833         -  0.042315
    two  0.705281      None -1.108522  0.471676

现在我需要为每个0级索引识别哪一行在第0列中具有最小数值,并为该行提取第3列的值。 (忽略NaN,无和 - )

例如,对于'bar',我比较-0.096648,NaN,-0.358526,其中最小的是-0.358526,所以我想要值0.284130(来自第3列)

我确信这很简单,但我对这些多索引表并不十分熟悉,只是迷失了方向而感到沮丧。

1 个答案:

答案 0 :(得分:2)

对索引使用DataFrameGroupBy.idxmin,但首先需要一些预处理,然后按DataFrame.iloc选择:

#get name for level of MultiIndex and create unique index
df1 = df.rename_axis(('a','b')).reset_index()
#if values non numeric in column 0 convert to NaNs
df1[0] = pd.to_numeric(df1[0], errors='coerce')
#get index of minimal values of column 0 per column a
s = df1.groupby('a')[0].idxmin()
print (s)
a
bar    2
baz    3
Name: 0, dtype: int64

#select by positions index and column 3
df = df.iloc[s, 3].to_frame()
print (df)
                3
bar thr  0.284130
baz one  0.042315
相关问题