Python Pandas Series.replace()

Python Pandas Series.replace()

Pandas系列是一个带有轴标签的一维ndarray。标签不需要是唯一的,但必须是一个可散列的类型。该对象支持基于整数和标签的索引,并提供了大量的方法来执行涉及索引的操作。

Pandas Series.replace()函数用于将to_replace中给出的值替换成数值。系列的值被动态地替换成其他的值。

语法: Series.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method=’pad’)

参数:
to_replace :如何找到将被替换的值。
value : 用来替换任何与to_replace匹配的值。
inplace : 如果是真的,就地取材。
limit :向前或向后填充的最大尺寸间隙。
regex : 是否将to_replace和/或value解释为正则表达式
method : 当to_replace是一个标量、列表或元组且值为None时,用于替换的方法。

返回:替换后的对象。

例子#1:使用Series.replace()函数从给定的Series对象中替换一些值。

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series([10, 25, 3, 11, 24, 6])
  
# Create the Index
index_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']
  
# set the index
sr.index = index_
  
# Print the series
print(sr)

输出 :

Python Pandas Series.replace()

现在我们将使用Series.replace()函数用新的数值替换旧的数值。

# replace 3 by 1000
result = sr.replace(to_replace = 3, value = 1000)
  
# Print the result
print(result)

输出 :

Python Pandas Series.replace()
正如我们在输出中看到的,Series.replace()函数已经成功地用新值替换了旧值。

例子#2 :使用Series.replace()函数来替换给定Series对象中的一些值。

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio'])
  
# Create the Index
index_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] 
  
# set the index
sr.index = index_
  
# Print the series
print(sr)

输出 :

Python Pandas Series.replace()

现在我们将使用Series.replace()函数,用一个列表将旧值替换为新值。

# replace the old ones in the list with 
# the new values
result = sr.replace(to_replace = ['New York', 'Rio'], value = ['London', 'Brisbane'])
  
# Print the result
print(result)

输出 :
Python Pandas Series.replace()
正如我们在输出中看到的,Series.replace()函数已经成功地使用列表将旧值替换为新值。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程