Pburg
Pburg

Reputation: 244

How can a define a new column based on the first character in another column? (Pandas)

I have a dataframe with a column, call it df['old'] of strings like the following.

a1bc  
df3   
ca9se 
3as3d 
iu23  

What I would like to do is create a new column that indicates if the value in the original column begins with one of a few characters.

Something like the following does not work as df['old'][0] returns a1bc.

df['new'] = df['old'][0] in ['a','b']

Is there a way to do this without using a loop? I don't know how to call a column and then just the first character value for that column.

Upvotes: 1

Views: 3124

Answers (1)

sacuL
sacuL

Reputation: 51405

You can use str to index your strings in each row, then use isin to check if it's in your list (using in will lead to ValueError: The truth value of a Series is ambiguous):

>>> df
     old
0   a1bc
1    df3
2  ca9se
3  3as3d
4   iu23

df['new'] = df.old.str[0].isin(['a','b'])

>>> df
     old    new
0   a1bc   True
1    df3  False
2  ca9se  False
3  3as3d  False
4   iu23  False

Upvotes: 5

Related Questions