Python是进行数据分析的优秀语言,主要是因为以数据为中心的Python软件包的奇妙生态系统。 熊猫 是使导入和分析数据更容易的软件包之一。
熊猫 提供3种方法来处理任何文本数据中的空白(包括新行)。从名字上可以看出, str.lstrip()
用于删除字符串左侧的空格, str.rstrip()
删除字符串右侧的空格,然后 str.strip()
从两侧移除空格。由于这些函数与Python的默认函数同名, str先生 必须加前缀才能告诉编译器正在调用Pandas函数。
语法: 系列str.strip()
返回类型: 带删除空格的级数
要下载代码中使用的CSV,请单击 在这里
在以下示例中,使用的数据框包含一些NBA球员的数据。由于数据框中的所有值都没有任何额外的空格,因此使用 str.replace() 方法任何操作之前的数据帧图像如下所示。
示例#1: 使用lstrip()
在本例中,创建了一个类似于团队列的新系列,该系列在字符串的开头和结尾都有两个空格。之后, str.lstrip()
方法,并根据已删除左侧空格的自定义字符串进行检查。
# importing pandas module import pandas as pd # making data frame # replacing team name and adding spaces in start and end new = data[ "Team" ].replace( "Boston Celtics" , " Boston Celtics " ).copy() # checking with custom removed space string new. str .lstrip() = = "Boston Celtics " |
输出: 如输出图像所示,删除左侧空格后,比较结果为真。
示例2: 使用strip()
在这个例子中, str.strip()
方法用于从字符串的左侧和右侧移除空格。将创建一个新的“团队”列副本,开始和结束处都有两个空格。然后 str.strip()
方法在该序列上被调用。之后,将其与“波士顿凯尔特人队”、“波士顿凯尔特人队”和“波士顿凯尔特人队”进行比较,以检查空间是否从两侧移除。
# importing pandas module import pandas as pd # making data frame # replacing team name and adding spaces in start and end new = data[ "Team" ].replace( "Boston Celtics" , " Boston Celtics " ).copy() # checking with custom string new. str .strip() = = " Boston Celtic" new. str .strip() = = "Boston Celtics " new. str .strip() = = " Boston Celtic " |
输出: 如输出图像所示,对于所有3种情况,比较结果都返回False,这意味着已成功从两侧删除空格,并且字符串不再具有空格。
示例#3: 使用rstrip()
在本例中,创建了一个类似于团队列的新系列,该系列在字符串的开头和结尾都有两个空格。之后 str.rstrip()
方法,并根据移除了右侧空格的自定义字符串进行检查。
# importing pandas module import pandas as pd # making data frame # replacing team name and adding spaces in start and end new = data[ "Team" ].replace( "Boston Celtics" , " Boston Celtics " ).copy() # checking with custom removed space string new. str .rstrip() = = " Boston Celtics" |
输出: 如输出图像所示,删除右侧空格后,比较结果为真。