How to remove a certain number of characters at the start of a string

Viewed 56

I have a dataset of NHL Free Agents, however they are numbered as a part of the name. I am trying to make "1. Alex Ovechkin" look like "Alex Ovechkin". Basically just trying to delete the number, period, and space between.

Dataset shown here

I have used the following code to successfully delete the numbers for the first 10 entries, however at entry 11 I need to delete 4 characters instead of 3. The same goes for row 100, I need to delete 5 characters to delete the numbers, period, and space.

This is the code that I have been trying to use to know avail.

free_agents['Player'] = free_agents['Player'].str[3:]

This works for the first 10 entries, but after that there is a space from 11-100, and a period and a space for the rest.

I also tried the following code, which worked for the first 10, but deleted the rest of the entries.

free_agents['Player'] = free_agents['Player'][0:10].str[3:]

My last attempt was to make a for loop, but did not work.

for player in free_agents['Player']:
    if player in free_agents['Player'][0:100]:
        free_agents = free_agents['Player'].str[2:]
    else: 
        free_agents['Player'] = free_agents['Player'].str[4:]

I've ran out of ideas to try, and would love some help in finding the most efficient way to do this. Thanks so much!

4 Answers

Assuming that no name starts with a number, you could try this:

free_agents['Player'] = free_agents['Player'].lstrip('0123456789. ')

This strips leading characters in the string matching:

  1. Any numbers between 0 and 9
  2. A period .
  3. A space .

split by . and get string index 1 of the output

df.Player=df.Player.str.split('\.\s').str[1]
df.Player = df.Player.str.split("\. ").str[1]

Based on regex

df["Player"] = df["Player"].str.replace("^\d+\.\s+", repl="", regex=True)
>>> df
          Player
0    1. Player A
1    2. Player B
2   10. Player C
3   11. Player D
4  100. Player E
5  101. Player F

df["Player"] = df["Player"].str.replace("^\d+\.\s+", repl="", regex=True)

>>> df
     Player
0  Player A
1  Player B
2  Player C
3  Player D
4  Player E
5  Player F
Related