SoFunction
Updated on 2024-10-28

A short summary of how to use the pandas replace function

Grammar:replace(self, to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad', axis=None)

The method of use is as follows:

import numpy as np 
import pandas as pd 
df = pd.read_csv('') 
df 

#Series object value replacement
s = [2]# Get row index 2 data
# Single-value substitution
('?',)# With replacement?
({'?':'NA'})#Replace with NA?
#Multi-value substitution
(['?',r'$'],[,'NA'])# List value replacement
({'?':,'$':'NA'})# Dictionary mapping
# Similar to the missing value filling method
(['?','$'],method='pad')# Fill forward
(['?','$'],method='ffill')# Fill forward
(['?','$'],method='bfill')# Backfill
The #limit parameter controls the number of fills
(['?','$'],method='bfill',limit=1)
#DataFrame object value replacement
# Single-value substitution
('?',)# With replacement?
({'?':'NA'})#Replace with NA?
# Specify single-value replacement by column
({'EMPNO':'?'},)# Replace the EMPNO column with ?
({'EMPNO':'?','ENAME':'.'},)#Replace the EMPNO column with ? and ENAME.
#Multi-value substitution
(['?','.','$'],[,'NA','None'])## Replace with? Replace $ with NA. Replace $ with None.
({'?':'NA','$':None})# Replace $ with NA? Replace $ with None
({'?','$'},{'NA',None})# Replace $ with NA? Replace $ with None
# Regular substitution
(r'\?|\.|\$',,regex=True)#With replacement? or . or $ original character
([r'\?',r'\$'],,regex=True)#with replacement? and $
([r'\?',r'\$'],[,'NA'],regex=True)# with substitution? Replace the $ sign with NA
(regex={r'\?':None})
#value parameter display pass
(regex=[r'\?|\.|\$'],value=)#replaced with?maybe.maybe$original character

This is a small summary of the use of the pandas replace function is all that I have shared with you, I hope to give you a reference, and I hope that you will support me more.