When working with data in python, it is common to encounter some elements whose content is not needed. They need to be deleted or replaced. This post explores in detail the deletion methods under various data types (series, dataframe)
Randomly create a DataFrame of data
import pandas as pd import numpy as np data=((10,size=(5,3)),columns=['a','b','c']) >>> a b c 0 3 8 2 1 9 9 5 2 4 5 1 3 2 7 5 4 1 2 8
Series:
The isin inverse function removes unwanted partial elements of a column, suitable for large quantities:
S data type directly use isin will be elected to the column contains the specified content, our demand is to delete the specified content need to use isin inverse function. But python currently does not have a function like isnotin, so we need to use the - sign to realize isnotin method
! = Comparison operator approach, suitable for a small number of cases or for use with conditions that satisfy both a and b.
isin:
Scenes from Series
print(data['c'][data['c'].isin([1])]) >>> 2 1 Name: c, dtype: int64 print(data['c'][-data['c'].isin([1])]) >>> 0 2 1 5 3 5 4 8 Name: c, dtype: int64 print(data['c'][-data['c'].isin([1,2])]) >>> 1 5 3 5 4 8 Name: c, dtype: int64
DataFrame Scene:
print(data[-([1,2])])#Operate df by Series logic to find that it will appear that the NAN is not removed >>> a b c 0 3.0 8.0 NaN 1 9.0 9.0 5.0 2 4.0 5.0 NaN 3 NaN 7.0 5.0 4 NaN NaN 8.0 print(data[-([1,2])].dropna())#We just need to add another dropna to remove nulls >>> a b c 1 9.0 9.0 5.0
! = Comparison operator:
Scenes from Series.
print(data['c'][data['c']!=1]) >>> 0 2 1 5 3 5 4 8 Name: c, dtype: int64 print(data['c'][(data['c']!=1)&((data['c']!=2))]) >>> 1 5 3 5 4 8 Name: c, dtype: int64
DataFrame Scene:
Delete data with different conditions for a and b respectively
print(data[(data['a']!=1)&(data['c']!=2)] >>> a b c 1 9 9 5 2 4 5 1 3 2 7 5 print(data[(data!=1)&(data!=2)].dropna()) # Same principle as isin a b c 1 9.0 9.0 5.0
The above python delete specified column or multiple columns single or multiple content example is all that I have shared with you, I hope to give you a reference, and I hope you support me more.