-
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
-
Stack
Stack¶
The stack function takes a dataframe and brings down each column. It can be tough to explain it so let’s just see what it looks like.
In [9]:
#Create the GDP object
gdp = pd.DataFrame([[.03, .04, .03],
[.05, .03, .01],
[.02, .02, .07],
[.03, .01, .02]], index=["Q1", "Q2", "Q3", "Q4"], columns=['Country A', "Country B", "Country C"])
print("Before stack:")
print(gdp)
print()
#Stack
gdp = gdp.stack()
print("After stack:")
print(gdp)
Before stack:
Country A Country B Country C
Q1 0.03 0.04 0.03
Q2 0.05 0.03 0.01
Q3 0.02 0.02 0.07
Q4 0.03 0.01 0.02
After stack:
Q1 Country A 0.03
Country B 0.04
Country C 0.03
Q2 Country A 0.05
Country B 0.03
Country C 0.01
Q3 Country A 0.02
Country B 0.02
Country C 0.07
Q4 Country A 0.03
Country B 0.01
Country C 0.02
dtype: float64
So you will see that we went from 4x3 dataframe to 12 values. One result of using this is that we now have a new type of index. Let's check out what we get out.
In [10]:
#Print out the GDP index after stacking
print(gdp.index)
MultiIndex([('Q1', 'Country A'),
('Q1', 'Country B'),
('Q1', 'Country C'),
('Q2', 'Country A'),
('Q2', 'Country B'),
('Q2', 'Country C'),
('Q3', 'Country A'),
('Q3', 'Country B'),
('Q3', 'Country C'),
('Q4', 'Country A'),
('Q4', 'Country B'),
('Q4', 'Country C')],
)
Prev
Clip
Next
Multi-Index