9

I would like a simple mehtod to delete parts of a string after a specified character inside a dataframe. Here is a simplified example:

df:

   obs         a  b  c  d
0    1   1-23-12  1  2  3
1    2  12-23-13  4  5  5
2    3  21-23-14  4  5  5

I would like to remove the parts in the a column after the first - sign, my expected output is:

newdf:

   obs   a  b  c  d
0    1   1  1  2  3
1    2  12  4  5  5
2    3  21  4  5  5
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
jonas
  • 13,559
  • 22
  • 57
  • 75

1 Answers1

15

You can reformat the values by passing a reformatting function into the apply method as follows:

from StringIO import StringIO
import pandas as pd

data = """   obs  a  b  c  d
1   1-23-12  1  2  3
2  12-23-13  4  5  5
3  21-23-14  4  5  5"""

# Build dataframe from data
df = pd.read_table(StringIO(data), sep='  ')

# Reformat values for column a using an unnamed lambda function
df['a'] = df['a'].apply(lambda x: x.split('-')[0])

This gives you your desired result:

   obs   a  b  c  d
0    1   1  1  2  3
1    2  12  4  5  5
2    3  21  4  5  5
joemar.ct
  • 1,206
  • 9
  • 14
  • Great!! Thats just what I wanted!! Thanks!! – jonas May 20 '14 at 19:04
  • 2
    It would be faster to use the `.str` method as this is vectorised so `df.a = df.a.str.split('-')[0]` should execute quicker – EdChum May 20 '14 at 19:27
  • I know this is a bit late, but is there a way to do this fast method if the column name has a space in it like "my name" but you don't want to change the name to "my_name" (because "df.my name" won't work but "df.my_name" does). – griffinc Apr 15 '17 at 03:18
  • You need `df['my name']`. When you have spaces in column name, access it via `df[col_name]` – Zero Sep 12 '17 at 05:37