Chandan N
Chandan N

Reputation: 51

How to Extract string from dataframe cell having both number and string

I have dataframe like this:

Mode  Small  medium Large
Car   20USD  40USD  60USD
Bike  10RS   30RS   45RS

Need it be like this:

Mode Currency Small Medium Large
Car  USD     20      40     60
Bike RS      10      30     45

Upvotes: 0

Views: 75

Answers (1)

Ilyas Moutawwakil
Ilyas Moutawwakil

Reputation: 109

Well there's two ways to do that:

  • The regex way which is pretty neat and straight forward (good thing you won't need the actual regex module since it's included in pandas series):
df['Currency'] = df['Small'].str.extract(r'\w+')
df['Small'] = df['Small'].str.extract(r'\d+').astype('int')
df['Medium'] = df['Medium'].str.extract(r'\d+').astype('int')
df['Large'] = df['Large'].str.extract(r'\d+').astype('int')

If everything goes right that should work.

  • The second way which is pretty ugly is to use loops and did I mention that it's ugly? anyways I recommand the first way.

Upvotes: 1

Related Questions