Is there an efficient way to drop n number of columns from a pandas df. For example, if you don't want anything past a certain column can you incorporate a function df.drop > n
For the df below I want to drop everything past column 2. I doing this via.
import pandas as pd
d = ({
'1' : ['X','Y'],
'2' : ['A','B'],
'3' : ['C','D'],
'4' : ['A','B'],
'5' : ['C','D'],
})
df = pd.DataFrame(data=d)
df = df.drop(['3','4','5'], axis = 1)
But if there are more or less than 5 columns I would have to manually add or subtract the column values. If I'm constantly doing this it becomes cumbersome.
df=df.iloc[:,:4], will keep colummns, 0,1,2,3df.iloc[:,:n]will drop everything after n columns. If the number of columns is less thannthen no error will occur.