shorttriptomars
shorttriptomars

Reputation: 325

How to extract first name in list

Hi so I'm printing out a list of usernames using the code below:

df1 = pd.DataFrame({'Username':commentor_list})
df1.assign(Username=df1.Username.str.split(",")).explode('Username')

However, some usernames output with extra info like the following:

Alice (10 videos / 58 subscribers)
Bob
Charles (20 videos / 28 subscribers)
Diana

I want to extract the first names to get

Alice 
Bob
Charles 
Diana

I've tried using the code below, as well as '[\S]' and '[\w] ' but nothing works. I get the error 'pattern contains no capture groups'

df1['Username'] = df1['Username'].str.extract('[?:\S]')
print(df1)

Can someone please help me? Thank you.

Upvotes: 2

Views: 163

Answers (1)

wasif
wasif

Reputation: 15478

There is no need of explode, I will use expand=True with .str.split:

df1['Username'] = df1['Username'].str.split(" ",expand=True)[0]

Upvotes: 3

Related Questions