-
Pandas Basics 5
-
Lecture1.1
-
Lecture1.2
-
Lecture1.3
-
Lecture1.4
-
Lecture1.5
-
-
Data Transformations 6
-
Lecture2.1
-
Lecture2.2
-
Lecture2.3
-
Lecture2.4
-
Lecture2.5
-
Lecture2.6
-
-
Statistics 4
-
Lecture3.1
-
Lecture3.2
-
Lecture3.3
-
Lecture3.4
-
-
Reading and Writing Data 3
-
Lecture4.1
-
Lecture4.2
-
Lecture4.3
-
-
Joins 5
-
Lecture5.1
-
Lecture5.2
-
Lecture5.3
-
Lecture5.4
-
Lecture5.5
-
-
Grouping 4
-
Lecture6.1
-
Lecture6.2
-
Lecture6.3
-
Lecture6.4
-
-
Introduction to Numpy 4
-
Lecture7.1
-
Lecture7.2
-
Lecture7.3
-
Lecture7.4
-
-
Randomness 2
-
Lecture8.1
-
Lecture8.2
-
-
Numpy Data Functionality 1
-
Lecture9.1
-
Multi-Index
Multi-index¶
After we have used stack, there are 12 values but also there is something new, a multi-index. What a multi-index does is essnetially instead of identifying each row with one value, there are tuples of values that identify them. You can still use loc, but you need to give a tuple. For example, to get the data for Q1 and country A, we feed that tuple in.
#Get back the value for Q1, Country A
print(gdp.loc[('Q1', 'Country A')])
0.03
You also can pass in a list of tuples to get multiple values back.
#Find multiple values
print(gdp.loc[[('Q1', 'Country A'),
('Q1', 'Country B')]])
Q1 Country A 0.03
Country B 0.04
dtype: float64
If you index with just one label (which needs to be the outer index label), you can get back only values equal to that. For example, if you wanted to get back only Q1 values, the following will achieve this:
print(gdp.loc["Q1"])
Country A 0.03
Country B 0.04
Country C 0.03
dtype: float64
You are also free to access the index values if you need them for any purpose with get_level_values. It needs an argument of which index to use. So for this case we can get the outer index with 0, inner index with 1.
#Get the outer index values
print(gdp.index.get_level_values(0))
Index(['Q1', 'Q1', 'Q1', 'Q2', 'Q2', 'Q2', 'Q3', 'Q3', 'Q3', 'Q4', 'Q4', 'Q4'], dtype='object')
#Get the inner index values
print(gdp.index.get_level_values(1))
Index(['Country A', 'Country B', 'Country C', 'Country A', 'Country B',
'Country C', 'Country A', 'Country B', 'Country C', 'Country A',
'Country B', 'Country C'],
dtype='object')