How to delete a column from a data frame with pandas?

前端 未结 3 1990
梦如初夏
梦如初夏 2020-12-24 11:00

I read my data

import pandas as pd
df = pd.read_csv(\'/path/file.tsv\', header=0, delimiter=\'\\t\')
print df

and get:

             


        
3条回答
  •  情书的邮戳
    2020-12-24 11:34

    The best way to delete a column in pandas is to use drop:

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

    where 1 is the axis number (0 for rows and 1 for columns.)

    To delete the column without having to reassign df you can do:

    df.drop('column_name', axis=1, inplace=True)
    

    Finally, to drop by column number instead of by column label, try this. To delete, e.g. the 1st, 2nd and 4th columns:

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


    Exceptions:

    If a wrong column number or label is requested an error will be thrown. To check the number of columns use df.shape[1] or len(df.columns.values) and to check the column labels use df.columns.values.

    An exception would be raised answer was based on @LondonRob's answer and left here to help future visitors of this page.

提交回复
热议问题