【问题标题】:How do I really use the `ix` method of a pandas DataFrame?我如何真正使用 pandas DataFrame 的 `ix` 方法?
【发布时间】:2012-08-16 08:37:20
【问题描述】:

注意:由于我提出了这个问题,.ix 仍然存在,但或多或​​少已被 .loc 用于基于标签的索引和.iloc 用于位置索引。


Having read the docs one the ix method of DataFrames,我对 MultiIndexed DataFrame(指定索引的选择列)的以下行为感到有些困惑。

In [57]: metals
Out[57]: 
<class 'pandas.core.frame.DataFrame'>
MultiIndex: 24245 entries, (u'BI', u'Arsenic, Dissolved', -2083768576.0, 1.0) 
                        to (u'WC', u'Zinc, Total',         1661183104.0, 114.0)
Data columns:
Inflow_val      20648  non-null values
Outflow_val     20590  non-null values
Inflow_qual     20648  non-null values
Outflow_qual    20590  non-null values
dtypes: float64(2), object(2)

In [58]: metals.ix['BI'].shape  # first column in the index, ok
Out[58]: (3368, 4)

In [59]: metals.ix['BI', :, :, :].shape  # first + other columns, ok
Out[59]: (3368, 4)

In [60]: metals.ix['BI', 'Arsenic, Dissolved'].shape # first two cols
Out[60]: (225, 4)

In [61]: metals.ix['BI', 'Arsenic, Dissolved', :, :].shape # first two + all others
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-62-1fb577ec32fa> in <module>()
----> 1 metals.ix['BI', 'Arsenic, Dissolved', :, :].shape                              
# traceback spaghetti snipped
KeyError: 'no item named Arsenic, Dissolved'

In [62]: metals.ix['BI', 'Arsenic, Dissolved', :, 1.0].shape # also fails

我花了很长时间才意识到,我一直试图通过 In [61] 实现的目标可以通过 In [60] 实现。为什么ix 方法的行为是这样的?我真正想要了解的是In [62] 的场景。

我的猜测是我需要重新定义索引层次结构,但我很好奇是否有更简单的方法。

谢谢。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    如果您想根据 MultiIndex 级别值选择行/列,我建议使用 '.xs()' 方法。另见Selecting rows from a Pandas dataframe with a compound (hierarchical) index

    对于这个例子,你可以使用:

    #short hand:
    metals.xs('BI', level=0).xs('Arsenic, Dissolved', level=0).xs(1, level=1)
    
    # more verbose
    metals.xs('BI', level='bmp_category').xs('Arsenic, Dissolved', level='parameter').xs(1, level='storm')
    
    # two chained `ix` calls:
    metals.ix['BI', 'Arsenic, Dissolved'].ix[:, 1]
    

    【讨论】:

      猜你喜欢
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-19
      • 2018-06-03
      • 2014-12-16
      • 2019-10-13
      • 1970-01-01
      相关资源
      最近更新 更多