简体   繁体   English

pandas MultiIndex:获取特定级别的值和 iloc

[英]pandas MultiIndex : Get value at a particular level and iloc

I am looking for the equivalent of at of DataFrame for MultiIndex .我正在为MultiIndex寻找相当于atDataFrame

My present implementation uses:我目前的实现使用:

mi = df.columns # This is a multi-index
mi.get_level_values(level_name)[i]

I am afraid this is not good for performance.恐怕这对性能不利。 Is there any other value to read a particular level at index i ?是否有任何其他值可以读取索引i处的特定level

Example:例子:

mi = pd.MultiIndex.from_product([[1,2,3], [4,5,6]], names=['i', 'j'])
df = pd.DataFrame({'x': range(9)}, index=mi)

df

     x
i j
1 4  0
  5  1
  6  2
2 4  3
  5  4
  6  5
3 4  6
  5  7
  6  8

df.index.get_level_values('j')[3]
4

Is there any short alternative to df.index.get_level_values('j')[3] df.index.get_level_values('j')[3]是否有任何简短的替代方案

If I understood correctly, I guess you could subset your DataFrame.如果我理解正确,我想您可以对 DataFrame 进行子集化。 Something like:就像是:

df.loc['level'] # In case there is more than one level: df.loc[('level1': 'level2')]

This will give you the row (or rows), and from there you can subset again vertically.这将为您提供行(或行),并且您可以从那里再次垂直子集。 Subsetting in both directions simultaneously would look something like:同时在两个方向上进行子集化看起来像:

df.loc['your_desired_column', 'level1': 'level2']

In case you have more than one index, the sintax to subset based on the outer index and the inner differs.如果您有多个索引,则基于外部索引和内部索引的子集的 sintax 会有所不同。

Outser: use strings Inner: use tuples Outser:使用字符串 Inner:使用元组

As in:如:

df.loc['level1':'level2'] # Outer
df.loc[('outer1', 'inner1'):('outer2', 'inner2')] # Outer & Inner

I hope you find this helpful!我希望这个对你有用!

Check Basic indexing on axis with MultiIndex documentation from pandas. 使用 pandas 中的 MultiIndex 文档检查轴上的基本索引

Here are some examples:这里有些例子:

In [18]: df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)

In [19]: df
Out[19]: 
first        bar                 baz                 foo                 qux          
second       one       two       one       two       one       two       one       two
A       0.895717  0.805244 -1.206412  2.565646  1.431256  1.340309 -1.170299 -0.226169
B       0.410835  0.813850  0.132003 -0.827317 -0.076467 -1.187678  1.130127 -1.436737
C      -1.413681  1.607920  1.024180  0.569605  0.875906 -2.211372  0.974466 -2.006747

In [25]: df['bar']
Out[25]: 
second       one       two
A       0.895717  0.805244
B       0.410835  0.813850
C      -1.413681  1.607920

In [26]: df['bar', 'one']
Out[26]: 
A    0.895717
B    0.410835
C   -1.413681
Name: (bar, one), dtype: float64

In [27]: df['bar']['one']
Out[27]: 
A    0.895717
B    0.410835
C   -1.413681
Name: one, dtype: float64

In [28]: s['qux']
Out[28]: 
one   -1.039575
two    0.271860
dtype: float64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM