Home  >  Article  >  Backend Development  >  How to use the drop() function in Python Pandas?

How to use the drop() function in Python Pandas?

王林
王林forward
2023-04-20 21:22:062046browse

Python basic pandas drop() usage

I used pandas when doing data processing, and the experience is good. The record is as follows:

import pandas as pd
import numpy as np

You can directly use pandas to generate a random array

df = pd.DataFrame(np.random.randn(5,3),index = list('abcde'),columns = ['one','two','three'])

How to use the drop() function in Python Pandas?

Assume there are empty numbers:

df.ix[1,:-1] = np.nan  #第二行,排除倒数第一个都是Nan
df.ix[1:-1,2] = np.nan #第三列,排除第一个和最后一个都是Nan

How to use the drop() function in Python Pandas?

Delete all the Nan ones

print('\n',df.dropna())

How to use the drop() function in Python Pandas?

Selectively delete, rather than delete Nan

print(df.drop(['one'],axis=1))
print(df.drop(['a','c'],axis = 0))

How to use the drop() function in Python Pandas?

Additional: python pandas drop() function

Use of drop function

(1) drop() delete rows and columns

drop([ ],axis=0,inplace=True)

  • ##drop([ ]), delete a certain row by default;

  • If you want to delete a column, axis=1 is required;

  • The parameter inplace is deleted by default False means keeping the original data unchanged, and True means changing the original data.

  • import pandas as pd
     
    import numpy as np
     
    data=pd.DataFrame(np.arange(20).reshape((5,4)),columns=list('ABCD'),index=['a','b','c','d','e'])
    print(data)
    print('*'*40)
    print(data.drop(['a'])) #删除a 行,默认inplace=False,
    print('*'*40)
    print(data)#  data 没有变化
    print('*'*40)
    print(data.drop(['A'],axis=1))#删除列
    print('*'*40)
    print(data.drop(['A'],axis=1,inplace=True)) #在本来的data 上删除
    print('*'*40)
    print(data)data 发生变化
     
        A   B   C   D
    a   0   1   2   3
    b   4   5   6   7
    c   8   9  10  11
    d  12  13  14  15
    e  16  17  18  19
    ****************************************
        A   B   C   D
    b   4   5   6   7
    c   8   9  10  11
    d  12  13  14  15
    e  16  17  18  19
    ****************************************
        A   B   C   D
    a   0   1   2   3
    b   4   5   6   7
    c   8   9  10  11
    d  12  13  14  15
    e  16  17  18  19
    ****************************************
        B   C   D
    a   1   2   3
    b   5   6   7
    c   9  10  11
    d  13  14  15
    e  17  18  19
    ****************************************
    None
    ****************************************
        B   C   D
    a   1   2   3
    b   5   6   7
    c   9  10  11
    d  13  14  15
    e  17  18  19

The above is the detailed content of How to use the drop() function in Python Pandas?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete