【发布时间】:2021-08-27 20:34:08
【问题描述】:
我有一个数据集,data1。我正在尝试使用基于input的索引切片
在哪里data1 =
stats
gender year
women 2003 cellphone use
2007 height
2007 cigarette use
2008 weight
2009 cellphone use
2015 cigarette use
2018 weight
2020 height
这是我对索引切片的尝试:
isvalid_yr = False
while not isvalid_yr:
year_input = int(input("Input the year you want to compare data from: "))
if year_input in data1.index.get_level_values('year')
idx = pd.IndexSlice
isvalid_yr = True
new_data1 = data1.loc(axis = 0)[idx[year_input:year_input], idx[:]]
else:
isvalid_yr = False
try:
if isvalid_yr ==True:
pass
else:
raise ValueError("Year not in data!")
except ValueError as err:
print("Year not in data!")
它给了我这个我不想要的输出。
Empty DataFrame
Columns: [stats]
Index: []
我想要实现的最终期望输出如下所示
Input the year you want to compare data from: 2007
new_data1 =的结果
stats
gender year
women
2007 height
2007 cigarette use
【问题讨论】:
-
这里有错误?
if prompt_yr in data1.index.get_level_values('year')prompt_yr 不应该是 year_input 吗? -
很好,谢谢!
标签: python pandas indexing hierarchical