How can I delete a dataframe column based on a certain string in its name?
Example:
house1 house2 chair1 chair2
index
1 foo lee sam han
2 fowler smith had sid
3 cle meg mag mog
I want to drop the columns that contain 'chair' in the string. How can this be done in an efficient way? Thanks.
During the data analysis operation on a dataframe, you may need to drop a column in Pandas. You can drop column in pandas dataframe using the df. drop(“column_name”, axis=1, inplace=True) statement.
Method 1 : Using dataframe. With this method, we can access a group of rows or columns with a condition or a boolean array. If we can access it we can also manipulate the values, Yes! this is our first method by the dataframe. loc[] function in pandas we can access a column and change its values with a condition.
Pandas Drop Multiple Columns By Index You can use df. columns[[index1, index2, indexn]] to identify the list of column names in that index position and pass that list to the drop method. Note that an index is 0 based. Use 0 to delete the first column and 1 to delete the second column and so on.
df.drop([col for col in df.columns if 'chair' in col],axis=1,inplace=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With