1

Say I have a list like this:

Words
One
Twos
Threes
Four
Fives
...
Thousand

Is there a relatively simple way to remove the 'S' from the end of the words? So it would become:

Words
One
Two
Three
Four
Five
...
Thousand
user3682157
  • 1,625
  • 8
  • 29
  • 55
  • 1
    Show us what you have done so far. – Neo Oct 15 '14 at 05:47
  • Sorry for the lazy question! Unfortunately I'm home now so I'll post what I've tried once I am in front of my computer tomorrow – user3682157 Oct 15 '14 at 05:52
  • See this: http://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string-in-python and you can use string[-1:] to get the last character. Do some magic and sort through the lines with "s" on the end – Winter Oct 15 '14 at 05:54

1 Answers1

1

You can use np.where to test if the last character is an 's' and if so remove it, otherwise use the existing value, this will be vectorised and much faster than a list comprehension:

In [14]:

df['Words'] = np.where(df['Words'].str[-1] == 's', df['Words'].str[:-1], df['Words'])
df
Out[14]:
      Words
0       One
1       Two
2     Three
3      Four
4      Five
5  Thousand

An alternative method which is likely to be even faster is to use loc and your condition to only strip the last character where it contains a trailing s, all other rows are left untouched:

In [18]:

df.loc[df['Words'].str[-1] == 's','Words'] = df['Words'].str[:-1]
df
Out[18]:
      Words
0       One
1       Two
2     Three
3      Four
4      Five
5  Thousand
EdChum
  • 376,765
  • 198
  • 813
  • 562