How to select all columns, except one column in pandas?

后端 未结 9 1794
不思量自难忘°
不思量自难忘° 2020-11-29 14:51

I have a dataframe look like this:

import pandas
import numpy as np
df = DataFrame(np.random.rand(4,4), columns = list(\'abcd\'))
df
      a         b                


        
9条回答
  •  难免孤独
    2020-11-29 15:29

    Don't use ix. It's deprecated. The most readable and idiomatic way of doing this is df.drop():

    >>> df
    
              a         b         c         d
    0  0.175127  0.191051  0.382122  0.869242
    1  0.414376  0.300502  0.554819  0.497524
    2  0.142878  0.406830  0.314240  0.093132
    3  0.337368  0.851783  0.933441  0.949598
    
    >>> df.drop('b', axis=1)
    
              a         c         d
    0  0.175127  0.382122  0.869242
    1  0.414376  0.554819  0.497524
    2  0.142878  0.314240  0.093132
    3  0.337368  0.933441  0.949598
    

    Note that by default, .drop() does not operate inplace; despite the ominous name, df is unharmed by this process. If you want to permanently remove b from df, do df.drop('b', inplace=True).

    df.drop() also accepts a list of labels, e.g. df.drop(['a', 'b'], axis=1) will drop column a and b.

提交回复
热议问题