Delete column from pandas DataFrame

后端 未结 17 1692
一生所求
一生所求 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
    

提交回复
热议问题