1. Use iloc Batch modify the data
2. After judging the data , mutual +/-/ Some number *
The first method : Use built-in functions where function
The second method : Use mask function
The third method :replace function
1. Use iloc Batch modify the dataUse iloc The simplest is to batch modify the data to a specific value
Here are the data I wrote casually :
You will now [‘d’,‘e’] Column ,[2,3,4] The data of the row is all modified to 0
import pandas as pddata = pd.read_excel('some_chaneg.xlsx')data1 = datadata1.iloc[2:5,3:] = 0data1
.iloc usage [], First, then , And they do not contain the last element , Take... For example [2,3,4] Namely [2:5], Columns also follow this rule
2. After judging the data , mutual +/-/ Some number * The first method : Use built-in functions where functionSeries.where(cond, other=nan, inplace=False, axis=None, level=None, errors='rais',...)
The explanation is if cond It's true , Then keep the original value , Otherwise replace with other, there cond and other Parameters are controlled by ourselves
# data2 by data Part of the data data2 = data.iloc[0:,1:]print(data2)data2.where(data2>25, data2+5,inplace=True)
selection data2 in <25 The data of , Add all 5
The second method : Use mask functionmask and where Just the opposite
mask(cond, other=nan)
where: Replacement conditions (condition) by False Place the value of the
mask: Replacement conditions (condition) by True Place the value of the
Or to data2 give an example
data2.mask(data2<25, data2+5, inplace=True)
The third method :replace function replace Text values can be replaced , You can also replace multiple values with dictionaries , You can also use regular expression nesting methods , Replace many different values
Replace text value :
# Replace text value data3 = datadata3.replace('wange', 'sheng', inplace=True)data3
Replace multiple values
Will all 0 and 1 swap :
# Replace multiple values # Will all 0 and 1 swap data3.replace({1:0,0:1},inplace=True)
Using regular expressions :
Change all that contain English letters into Anonymous
# Remember to use regular expressions , Be sure to add regex=Truedata3.replace('[a-zA-Z]+','Anonymous',regex=True,inplace=True)
This is about pandas Dataframe This is the end of the article on implementing the method of batch modifying values , More about pandas Please search the previous articles of SDN or continue to browse the related articles below. I hope you will support SDN more in the future !