user92033
0
Q:

pandas drop columns by index

# Let df be a dataframe
# Let new_df be a dataframe after dropping a column

new_df = df.drop(labels='column_name', axis=1)

# Or if you don't want to change the name of the dataframe
df = df.drop(labels='column_name', axis=1)

# Or to remove several columns
df = df.drop(['list_of_column_names'], axis=1)

# axis=0 for 'rows' and axis=1 for columns
3
df.drop(columns=['B', 'C'])
4
note: df is your dataframe

df = df.drop('coloum_name',axis=1)
5
df = df.drop(['B', 'C'], axis=1)
4
>>> df.drop(columns=['B', 'C'])
   A   D
0  0   3
1  4   7
2  8  11
0
cols = [1,2,4,5,12]
df.drop(df.columns[cols],axis=1,inplace=True)
0
del df['column_name']
0
>>> midx = pd.MultiIndex(levels=[['lama', 'cow', 'falcon'],
...                              ['speed', 'weight', 'length']],
...                      codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2],
...                             [0, 1, 2, 0, 1, 2, 0, 1, 2]])
>>> df = pd.DataFrame(index=midx, columns=['big', 'small'],
...                   data=[[45, 30], [200, 100], [1.5, 1], [30, 20],
...                         [250, 150], [1.5, 0.8], [320, 250],
...                         [1, 0.8], [0.3, 0.2]])
>>> df
                big     small
lama    speed   45.0    30.0
        weight  200.0   100.0
        length  1.5     1.0
cow     speed   30.0    20.0
        weight  250.0   150.0
        length  1.5     0.8
falcon  speed   320.0   250.0
        weight  1.0     0.8
        length  0.3     0.2
0

New to Communities?

Join the community