python – 按索引选择MultiIndex数据框中的行而不会丢失任何级别
作者:互联网
我想选择一个名为’Mid’的行,而不会丢失它的索引’Site’
以下代码显示了数据帧:
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
以下答案给出了预期的结果:
m.commodity.xs('Mid', drop_level=False)
m.commodity.loc[['Mid']]
m.commodity.loc['Mid', :, :]
ty MaxU,COLDSPEED和jezrael的答案:)
解决方法:
你也可以使用带双括号的loc.
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’]].
在讨论loc与ix时,不推荐使用后者,请使用loc / iloc / iat / xs进行索引.
ix对传递的内容做出假设,并接受标签或位置. loc纯粹基于标签,而iloc纯粹是索引(基于位置)
标签:multi-index,python,pandas,dataframe 来源: https://codeday.me/bug/20191002/1840744.html