[英]How to access specific rows in a pandas multiindex dataframe
I'm working with what I think is a pandas multi-index data frame.我正在使用我认为是 Pandas 多索引数据框。 Is there any way to make sure?
有什么办法可以确定吗? My data looks like this.
我的数据看起来像这样。
cinc Outcome
Side 1 2 1 2
WarNum
1 0.146344 0.029989 1 2
4 0.152565 0.056853 1 2
7 0.082757 0.017940 1 2
10 0.076032 0.022553 1 2
13 0.048538 0.005754 1 2
When I type in war_cinc.columns.当我输入 war_cinc.columns 时。 I get the following output.
我得到以下输出。
MultiIndex([( 'cinc', 1),
( 'cinc', 2),
('Outcome', 1),
('Outcome', 2)],
names=[None, 'Side'])
If I wanted to subset this data, how would I do so?如果我想对这些数据进行子集化,我该怎么做? (say I want to get the entire 2nd column of the cinc column of the dataframe)
(假设我想获取数据框 cinc 列的整个第二列)
To check if your df has Multiindex
, you can do this:要检查您的 df 是否具有
Multiindex
,您可以执行以下操作:
isinstance(war_cinc.index, pd.MultiIndex)
This will return True
.这将返回
True
。
To check for hierarchical
columns, you can check nlevels
:要检查
hierarchical
列,您可以检查nlevels
:
if len(war_cinc.columns.nlevels) > 1:
This will be True
in your case.在您的情况下,这将是
True
。
You can get the entire 2nd column like:您可以获得整个第二列,例如:
war_cinc[( 'cinc', 2)]
You need to pass all levels
of the column in a tuple
to fetch the column values.您需要在
tuple
传递列的所有levels
以获取列值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.