Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Separate a word from a number python

I have a dataframe with 1 column containing the amount bought of a particular crypto

df['Amount'] = 200.20356AVAX

I would like to split this object into 2 columns:

  • 1 containing the number –> df['Quantity'] = 200.20356
  • 1 containing the word –> df['Asset'] = AVAX

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use str.extract:

df = pd.DataFrame({'Amount': ['200.20356AVAX']})

df = df.join(df['Amount'].str.extract('([^A-Z]+)([A-Z]+)') \
                         .rename(columns={0: 'Quantity', 1: 'Asset'}))

# OR, proposed by @mozway (more efficient)

df = df.join(df['Amount'].str.extract('(?P<Quantity>[^A-Z]+)(?P<Asset>[A-Z]+)'))

Output:

>>> df
          Amount   Quantity Asset
0  200.20356AVAX  200.20356  AVAX
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading