Lisle
Lisle

Reputation: 1690

Slicing Part of a column Pandas

I have a dataframe with column 'A' as a string. Within 'A' there are values like name1-L89783 nametwo-L33009

I would like to make a new column 'B' such that the '-Lxxxx' is removed and all that remains is 'name1' and 'nametwo'.

Upvotes: 0

Views: 58

Answers (2)

mechanical_meat
mechanical_meat

Reputation: 169274

Initialize DataFrame.

df = pd.DataFrame(['name1-L89783','nametwo-L33009'],columns=['A',])

>>> df
                A
0    name1-L89783
1  nametwo-L33009

Apply function over rows and put the result in a new column.

df['B'] = df['A'].apply(lambda x: x.split('-')[0])

>>> df
                A        B
0    name1-L89783    name1
1  nametwo-L33009  nametwo

Upvotes: 1

EdChum
EdChum

Reputation: 393893

use vectorised str.split for this and then use str again to access the array element of interest in this case the first element of the split:

In [10]:
df[1] = df[0].str.split('-').str[0]
df

Out[10]:
                0        1
0    name1-L89783    name1
1  nametwo-L33009  nametwo

Upvotes: 2

Related Questions