Delete column from pandas DataFrame

后端 未结 17 1373
一生所求
一生所求 2020-11-22 02:44

When deleting a column in a DataFrame I use:

del df[\'column_name\']

And this works great. Why can\'t I use the following?

         


        
相关标签:
17条回答
  • 2020-11-22 03:33

    Drop by index

    Delete first, second and fourth columns:

    df.drop(df.columns[[0,1,3]], axis=1, inplace=True)
    

    Delete first column:

    df.drop(df.columns[[0]], axis=1, inplace=True)
    

    There is an optional parameter inplace so that the original data can be modified without creating a copy.

    Popped

    Column selection, addition, deletion

    Delete column column-name:

    df.pop('column-name')
    

    Examples:

    df = DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6]), ('C', [7,8, 9])], orient='index', columns=['one', 'two', 'three'])
    

    print df:

       one  two  three
    A    1    2      3
    B    4    5      6
    C    7    8      9
    

    df.drop(df.columns[[0]], axis=1, inplace=True) print df:

       two  three
    A    2      3
    B    5      6
    C    8      9
    

    three = df.pop('three') print df:

       two
    A    2
    B    5
    C    8
    
    0 讨论(0)
  • 2020-11-22 03:33
    df.drop('columnname', axis =1, inplace = True)
    

    or else you can go with

    del df['colname']
    

    To delete multiple columns based on column numbers

    df.drop(df.iloc[:,1:3], axis = 1, inplace = True)
    

    To delete multiple columns based on columns names

    df.drop(['col1','col2',..'coln'], axis = 1, inplace = True)
    
    0 讨论(0)
  • 2020-11-22 03:35

    It's good practice to always use the [] notation. One reason is that attribute notation (df.column_name) does not work for numbered indices:

    In [1]: df = DataFrame([[1, 2, 3], [4, 5, 6]])
    
    In [2]: df[1]
    Out[2]:
    0    2
    1    5
    Name: 1
    
    In [3]: df.1
      File "<ipython-input-3-e4803c0d1066>", line 1
        df.1
           ^
    SyntaxError: invalid syntax
    
    0 讨论(0)
  • 2020-11-22 03:40

    The actual question posed, missed by most answers here is:

    Why can't I use del df.column_name?

    At first we need to understand the problem, which requires us to dive into python magic methods.

    As Wes points out in his answer del df['column'] maps to the python magic method df.__delitem__('column') which is implemented in pandas to drop the column

    However, as pointed out in the link above about python magic methods:

    In fact, __del__ should almost never be used because of the precarious circumstances under which it is called; use it with caution!

    You could argue that del df['column_name'] should not be used or encouraged, and thereby del df.column_name should not even be considered.

    However, in theory, del df.column_name could be implemeted to work in pandas using the magic method __delattr__. This does however introduce certain problems, problems which the del df['column_name'] implementation already has, but in lesser degree.

    Example Problem

    What if I define a column in a dataframe called "dtypes" or "columns".

    Then assume I want to delete these columns.

    del df.dtypes would make the __delattr__ method confused as if it should delete the "dtypes" attribute or the "dtypes" column.

    Architectural questions behind this problem

    1. Is a dataframe a collection of columns?
    2. Is a dataframe a collection of rows?
    3. Is a column an attribute of a dataframe?

    Pandas answers:

    1. Yes, in all ways
    2. No, but if you want it to be, you can use the .ix, .loc or .iloc methods.
    3. Maybe, do you want to read data? Then yes, unless the name of the attribute is already taken by another attribute belonging to the dataframe. Do you want to modify data? Then no.

    TLDR;

    You cannot do del df.column_name because pandas has a quite wildly grown architecture that needs to be reconsidered in order for this kind of cognitive dissonance not to occur to its users.

    Protip:

    Don't use df.column_name, It may be pretty, but it causes cognitive dissonance

    Zen of Python quotes that fits in here:

    There are multiple ways of deleting a column.

    There should be one-- and preferably only one --obvious way to do it.

    Columns are sometimes attributes but sometimes not.

    Special cases aren't special enough to break the rules.

    Does del df.dtypes delete the dtypes attribute or the dtypes column?

    In the face of ambiguity, refuse the temptation to guess.

    0 讨论(0)
  • 2020-11-22 03:42

    The best way to do this in pandas is to use drop:

    df = df.drop('column_name', 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 = df.drop(df.columns[[0, 1, 3]], axis=1)  # df.columns is zero-based pd.Index 
    

    Also working with "text" syntax for the columns:

    df.drop(['column_nameA', 'column_nameB'], axis=1, inplace=True)
    

    Note: Introduced in v0.21.0 (October 27, 2017), the drop() method accepts index/columns keywords as an alternative to specifying the axis.

    So we can now just do:

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

    0 讨论(0)
提交回复
热议问题