Chique_Code
Chique_Code

Reputation: 1530

Remove last char in a string for each row in pandas df

I have a pandas dataframe with column keys, I need to remove the last character from each string.

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

Currently, I am trying to create a function that would return a clean string and I would apply the function to df later. I tried the following:

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) 

It returns an empty string. And I want it to return "url_test = "https://www.cosmopolitan.com/entertainment/tv"

Upvotes: 11

Views: 45568

Answers (3)

mikeqfu
mikeqfu

Reputation: 328

If your column key contains all values of str type, and you would like to apply (or rather, map) the function to the column, you could simply use rstrip (or just strip) without defining a function.

Suppose your given pandas dataframe is named as df, try:

new_keys = df['keys'].str.rstrip('/')

The new_keys is a pandas series.

Upvotes: 1

tomjn
tomjn

Reputation: 5389

You can use pandas string accessor methods

e.g.

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]

will trim the last character from the string. This allows you to operate on the entire column rather than one row at a time.

Upvotes: 15

Sayse
Sayse

Reputation: 43300

Just remove the for loop, you're passing in a string, then iterating over the characters, and returning the first character without the first character, hence an empty string.

def clean_string(url):
    return url[:-1]

Although I'm not sure you'd still need a function to do this.

If you're just trying to remove the trailing slash, you may prefer to use rstrip

return url.rstrip("/")

Upvotes: 2

Related Questions