How to Select the First n Columns of a Pandas DataFrame
How can we select the first n
columns of a Pandas DataFrame?
Suppose we have this DataFrame df
.
x1 x2 x3 x4 y
0 7 143 22 23 1
1 1 23 22 29 0
2 3 133 24 0 1
3 1 39 27 23 0
4 0 137 40 23 1
If we only want the first 4
columns, then we can either slice by the actual index, or use -1
.
df.iloc[:,:4]
df.iloc[:,:-1]
If we only want the last column (index of 4
), once again, we can either slice by the actual index, or use -1
.
df.iloc[:,4:]
df.iloc[:,-1:]