删除 pandas df 中每一行的字符串中的最后一个字符

Chi*_*ode 11 python

我有一个带有 column 的 pandas 数据框keys,我需要从每个字符串中删除最后一个字符。

id       keys     
123      "https://www.cosmopolitan.com/entertainment/tv/a46533/"
124      "https://www.bazaar.com/entertainment/tv/a46533/"
Run Code Online (Sandbox Code Playgroud)

目前,我正在尝试创建一个返回干净字符串的函数,稍后我会将该函数应用于 df 。我尝试了以下方法:

url_test = "https://www.cosmopolitan.com/entertainment/tv/"

def clean_string(url):
    for string in url:
        new_string = string[:-1]
        return new_string
clean_string(url_test) 
Run Code Online (Sandbox Code Playgroud)

它返回一个空字符串。我希望它回来"url_test = "https://www.cosmopolitan.com/entertainment/tv"

tom*_*mjn 14

您可以使用 pandas字符串访问器方法

例如

import pandas as pd 
test = pd.Series([
    "https://www.cosmopolitan.com/entertainment/tv/a46533/",
    "https://www.bazaar.com/entertainment/tv/a46533/"])
test = test.str[:-1]
Run Code Online (Sandbox Code Playgroud)

将从字符串中删除最后一个字符。这允许您一次对整列而不是一行进行操作。


Say*_*yse 2

只需删除 for 循环,您将传入一个字符串,然后迭代字符,并返回第一个字符而不返回第一个字符,因此是一个空字符串。

def clean_string(url):
    return url[:-1]
Run Code Online (Sandbox Code Playgroud)

尽管我不确定您是否仍然需要一个函数来执行此操作。

如果您只是想删除尾部斜杠,您可能更喜欢使用rstrip

return url.rstrip("/")
Run Code Online (Sandbox Code Playgroud)