Transposing with pd.DataFrame.T
For the final recipe in this chapter, let’s explore one of the easier reshaping features of pandas. Transposition refers to the process of inverting your pd.DataFrame
so that the rows become the columns and the columns become the rows:
Figure 7.8: Transposing a pd.DataFrame
In this recipe, we will see how to transpose with the pd.DataFrame.T
method while discussing how this might be useful.
How to do it
Transposition in pandas is straightforward. Take any pd.DataFrame
:
df = pd.DataFrame([
[1, 2, 3],
[4, 5, 6],
], columns=list("xyz"), index=list("ab"))
df
x y z
a 1 2 3
b 4 5 6
You can simply access the pd.DataFrame.T
attribute and watch as your rows become your columns and your columns become your rows:
df.T
a b
x 1 4
y 2 5
z 3 6
There are an endless number of reasons why you may want to transpose, ranging from simply thinking it...