在不丢失任何级别的情况下按索引选择MultiIndex数据框中的行 [英] Selecting rows in a MultiIndex dataframe by index without losing any levels
问题描述
我想选择一个名为"Mid"的行,而不会丢失其索引"Site"
I would like to select a row called 'Mid', without losing it's index 'Site'
以下代码显示了数据框:
Following code shows the dataframe:
m.commodity
price max maxperstep
Site Commodity Type
Mid Biomass Stock 6.0 inf inf
CO2 Env 0.0 inf inf
Coal Stock 7.0 inf inf
Elec Demand NaN NaN NaN
Gas Stock 27.0 inf inf
Hydro SupIm NaN NaN NaN
Lignite Stock 4.0 inf inf
Slack Stock 999.0 inf inf
Solar SupIm NaN NaN NaN
Wind SupIm NaN NaN NaN
North Biomass Stock 6.0 inf inf
CO2 Env 0.0 inf inf
Coal Stock 7.0 inf inf
Elec Demand NaN NaN NaN
Gas Stock 27.0 inf inf
Hydro SupIm NaN NaN NaN
Lignite Stock 4.0 inf inf
Slack Stock 999.0 inf inf
Solar SupIm NaN NaN NaN
Wind SupIm NaN NaN NaN
South Biomass Stock 6.0 inf inf
CO2 Env 0.0 inf inf
Coal Stock 7.0 inf inf
Elec Demand NaN NaN NaN
Gas Stock 27.0 inf inf
Hydro SupIm NaN NaN NaN
Lignite Stock 4.0 inf inf
Slack Stock 999.0 inf inf
Solar SupIm NaN NaN NaN
Wind SupIm NaN NaN NaN
期望的结果如下:
price max maxperstep
Site Commodity Type
Mid Biomass Stock 6.0 inf inf
CO2 Env 0.0 inf inf
Coal Stock 7.0 inf inf
Elec Demand NaN NaN NaN
Gas Stock 27.0 inf inf
Hydro SupIm NaN NaN NaN
Lignite Stock 4.0 inf inf
Slack Stock 999.0 inf inf
Solar SupIm NaN NaN NaN
Wind SupIm NaN NaN NaN
以下答案给出了理想的结果:
following answers give the desired outcome:
m.commodity.xs('Mid', drop_level=False)
m.commodity.loc[['Mid']]
m.commodity.loc['Mid', :, :]
ty MaxU,COLDSPEED和jezrael给出的答案:)
ty MaxU, COLDSPEED and jezrael for the answers :)
推荐答案
您也可以将loc
与大括号一起使用.
You can also use loc
with double braces.
df.loc[['Mid']]
price max maxperstep
Site Commodity Type
Mid Biomass Stock 6.0 inf inf
CO2 Env 0.0 inf inf
Coal Stock 7.0 inf inf
Elec Demand NaN NaN NaN
Gas Stock 27.0 inf inf
Hydro SupIm NaN NaN NaN
Lignite Stock 4.0 inf inf
Slack Stock 999.0 inf inf
Solar SupIm NaN NaN NaN
Wind SupIm NaN NaN NaN
在您的情况下,我想它应该是m.commodity.loc[['Mid']]
.
In your case, I'd suppose it would be m.commodity.loc[['Mid']]
.
当谈论loc
与ix
是因为后者已被弃用时,请使用loc
/iloc
/iat
/xs
进行索引.
When talking about loc
versus ix
is that the latter is deprecated, use loc
/iloc
/iat
/xs
for indexing.
ix
对传递的内容进行假设,并接受标签或位置. loc
完全基于标签,而iloc
完全基于索引(基于位置)
ix
makes assumptions about what is passed, and accepts either labels or positions. loc
is purely label based, while iloc
is purely index (positional based)
这篇关于在不丢失任何级别的情况下按索引选择MultiIndex数据框中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!