drop list of columns pandas code example

Example 1: drop multiple columns pandas

yourdf.drop(['columnheading1', 'columnheading2'], axis=1, inplace=True)

Example 2: drop columns pandas

df.drop(columns=['B', 'C'])

Example 3: how to drop columns in pandas

>>>df = pd.DataFrame(np.arange(12).reshape(3, 4), 
                     columns=['A', 'B', 'C', 'D'])
>>>df
   A  B   C   D
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11

>>> df.drop(['B', 'C'], axis=1)
   A   D
0  0   3
1  4   7
2  8  11

OR

>>> df.drop(columns=['B', 'C'])
   A   D
0  0   3
1  4   7
2  8  11

Example 4: drop list of columns pandas

df.drop([item for item in total_cols if item not in columns_in_use], axis=)

Example 5: remove columns from a dataframe python

df = df.drop(df.columns[[0, 1, 3]], axis=1)  # df.columns is zero-based pd.Index

Example 6: python - dataframe columns is a list - drop

# Df with a coulmn (dims) that contain list
key1 = 'site channel fiscal_week'.split()
key2 = 'site dude fiscal_week'.split()
key3 = 'site eng fiscal_week'.split()

keys = pd.DataFrame({'key': [1,2,3],
                     'dims': [key1,key2,key3]})

# Output
                         dims  key
[site, channel, fiscal_week]    1
[site, dude, fiscal_week]       2
[site, eng, fiscal_week]        3


# Solution
keys['reduced_dims'] = keys['dims'].apply(
    lambda row: [val for val in row if val != 'fiscal_week']
)