SoFunction
Updated on 2024-10-28

Replace function in Pandas to use those things!

I. Series Data Replacement()

(pat,repl,n=-1,case=None,flags=0,regex=None)

Functions in detail:

pat String to find
repl The replaced string can be called with the function
n Number of substitutions to be made, default all
case case sensitive or not
flags Flags in the re module
regex Whether to set it as a regular expression

1. General search and replace

Replace Cao Cao with Liu Bei

import pandas as pd
s=(['Cao Cao','Big Joe','Little Joe'])
('Cao Cao','Liu Bei')

2. Regular expression replacement

Replace '~' and '/' in strings with '-'

import pandas as pd
s=(['2022-5-5','2022/5/6','2022~6~9'])
('[~/]','-',regex=True)

3. Pre-compiled regular expression replacement

Replace '~' and '/' in strings with '-'

import pandas as pd
import re
s=(['2022-5-5','2022/5/6','2022~6~9'])
pat=('[~/]')
(pat,'-',regex=True)

4. Function replacement

Add parentheses to the names of people in the Series; add '-' between the name and the date.

import pandas as pd
import re
s=(['Aaron2022-5-5','Bob2022-5-6','judy2022-6-9'])
('[a-zA-Z]+',lambda x: '('+x[0]+')'+'-',regex=True)

5. Substitution in groups

In a different way, group substitution can accomplish the same thing as function substitution;

s=(['Aaron2022-5-5','Bob2022-5-6','judy2022-6-9'])
('([a-zA-Z]+)',r"【\1】-",regex=True)

II. DataFrame Data Replacement ()

(to_replace=None,value=None,inplace=False,limit=None,regex=False,method='pad)

Functions in detail:

to_replace Find the value to replace
value Replacement of values matching the lookup
inplace Modify original data
limit Maximum size gap for forward or backward filling
regex Whether regular expressions are supported
method Replacement method

1. Single-value substitution

Write the instance data:

df=({'Hero Attributes':['Assassin','Shooter','Mage','Warrior','Auxiliary'],
                'Red's Heroes':['Jing Ke','Halogen Eggs','Zhen Ji','Xiahou Dun','Xiang Yu'],
                'Red damage':[11.20,15.34,8.57,6.98,3.69],
                 'Number of deaths on the red side':['1 time','10 times','8 times','5 times','6 times'],
                'Heroes of the blue side':['Zhao Yun','Mark','Dry General','Lü Bu','Liu Zen'],
                'Blue damage':[10.82,11.36,10.87,9.69,6.53],
                'Number of deaths on the blue side':['5 times','8 times','4 times','7 times','10 times']})
df

Replace Jing Ke with Sun Wukong;

('Jing Ke','Monkey King')

2. List replacement

Multiple values replace a single value, replacing Zhao Yun and Mark with Sun Ce

(['Zhao Yun','Mark'],'Sun Ce')

Multiple values replace multiple values, replacing Zhao Yun and Mark with Orange Righteousness and Yuji;

The lookup values are placed in a list, and the replacement values are placed in a list that needs to correspond one to the other;

(['Zhao Yun','Mark'],['Orange Righteousness','Yu Ji'])

3. Dictionary substitution

(1) Dictionary substitution, replacing Zhao Yun and Mark with Orange Right and Yu Ji

The key passed into the dictionary is the value to look up and the value is the value to replace;

({
    'Zhao Yun':'Orange Righteousness',
    'Mark':'Yu Ji'
})

(2) Specify column replacement

Replace the red hero Zhen Ji with Sable Cicada and Xiang Yu with Zhong Kui; the blue hero Lu Bu with Sun Ce and Gan with Yang Yuhuan;

({
    'Red's Heroes':{
        'Zhen Ji':'Sable Cicada',
        'Xiang Yu':'Zhong Kui'
    },
    'Heroes of the blue side':{
        'Lü Bu':'Sun Ce',
        'Dry General':'Yang Yuhuan'
    }
})

 (3) Multi-column replacement

Replace Red's damage of 11.2 and Blue's damage of 11.36, 9.69 with 9.999

({'Red damage':11.2,'Blue damage':[11.36,9.69]},9.999)

III. DataFrame Regular Replacement

1. Introduction to 'zero-width assertions' for regular expressions

name (of a thing) displayed formula account for
Zero-width positive prior assertion (?=exp) Matches a string followed by an exp expression.
Zero-width negative prior assertion (?!exp) Matches a string that is not followed by an exp expression.
Zero-width positive backward assertion (?<=exp) Matches a string preceded by an exp expression.
Zero-width negative backward-looking assertion (?<!exp) Matches a string that is not preceded by an exp expression.

2. Single-value regular substitution

Add '-' between the number of deaths on the red side and the number of deaths on the blue side and 'times'

(
    to_replace='(^\d+)(?=\D)',
    value=r'\1-',
    regex=True
)

3. List regular substitution

List Replacement, add '[ ]' to Red's heroes

df['Red's Heroes']=df['Red's Heroes'].replace(
    regex=['^','$'],
    value=['【','】'],
)
df

4. Dictionary regular substitution

Dictionary Regular Replacement, add '[]' to blue heroes

(
regex={
    'Heroes of the blue side':{'^':'[','$':']'}
})

IV. DataFrame Replacement Example Applications

The original data is as follows: the number following the hero information column is the number;

df=({'Hero Attributes':['Assassin','Shooter','Mage','Warrior','Auxiliary'],
                 'Hero Information':['Thornhorn 36','Halogen Eggs 1','Zhen Ji 6','Xiahou Dun 10','Xiang Yu 66'],
                'Red's Heroes':['Jing Ke','Halogen Eggs','Zhen Ji','Xiahou Dun','Xiang Yu'],
                'Red damage':[11.20,15.34,8.57,6.98,3.69],
                 'Number of deaths on the red side':['1 time','10 times','8 times','5 times','6 times'],
                'Heroes of the blue side':['Zhao Yun','Mark','Dry General','Lü Bu','Liu Zen'],
                'Blue damage':[10.82,11.36,10.87,9.69,6.53],
                'Number of deaths on the blue side':['5 times','8 times','4 times','7 times','10 times']})
df

 1. Harmonize the numbering to four digits, using zeros to make up any shortfall of four digits;

df['Hero Information'].(
    pat='(\d+)',
    repl=lambda x: '0'*(4-len(x[0]))+x[0],
    regex=True
)

2. Precede the number with Timi and use '-' as a delimiter.

df['Hero Information']=df['Hero Information'].(
    pat='(\d+)',
    repl=lambda x: '-Timi'+'0'*(4-len(x[0]))+x[0],
    regex=True
)
df

summarize

to this article on the use of Pandas Replace function is introduced to this article, more related to the use of Pandas Replace function, please search for my previous posts or continue to browse the following articles I hope you will support me more in the future!