首页 > 解决方案 > 删除pandas df中每一行的字符串中的最后一个字符

问题描述

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

id       keys     
123      "https://www.cosmopolitan.com/entertainment/tv/a46533/"
124      "https://www.bazaar.com/entertainment/tv/a46533/"

目前,我正在尝试创建一个返回干净字符串的函数,稍后我会将该函数应用于 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) 

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

标签: python

解决方案


您可以使用 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]

将修剪字符串中的最后一个字符。这使您可以对整列进行操作,而不是一次操作一行。


推荐阅读