Python| Pandas Series.str.slice_replace()
Python是一种用于进行数据分析的出色语言,主要是因为以数据为中心的Python包的奇妙生态系统。 Pandas就是其中之一,它使导入和分析数据变得更加容易。
Pandas str.slice_replace()
方法用于替换 Pandas 系列对象中存在的切片字符串。由于这是一个 pandas字符串方法,因此每次调用此方法之前都必须添加.str前缀。否则,它会给出错误。
Syntax: Series.str.slice_replace(start=None, stop=None, repl=None)
Parameters:
start: int value, tells where to start slicing
stop: int value, tells where to end slicing
repl: string value, replaces the sliced substring with this
Return type: Series with replaced values
要下载代码中使用的 CSV,请单击此处。
在以下示例中,使用的数据框包含一些 NBA 球员的数据。下面附上任何操作之前的数据帧图像。
例子 :
在这个例子中,salary 列已被切片以获取小数点后的值,并且这些值('.0' 被'$' 符号替换)。由于薪水列是作为 float64 数据类型导入的,因此首先使用 .astype() 方法将其转换为字符串。
# importing pandas module
import pandas as pd
# making data frame
data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")
# removing null values to avoid errors
data.dropna(inplace = True)
# start stop and step variables
start, repl = -2, '$'
# converting to string data type
data["Salary"]= data["Salary"].astype(str)
# slicing till 2nd last element
data["Salary New"]= data["Salary"].str.slice_replace(start = start, repl = repl)
# display
data.head(10)
输出:
如输出图像所示,Salary New 列具有替换值。使用 .slice_replace() 方法将“.0”替换为“$”。