简体   繁体   中英

python pandas how to extract number from string?

I have an dataframe and I want to extract only number from string and appoint theme another new row.

dataframe:

 type
gp250,sp280

expected result for dataframe:

type   price
gp      25
sp      280

You can use a regular expression to extract the consecutive digits of the string and then explode to transform the result into multiple rows.

import re
df["type"].apply(lambda x: re.findall("([0-9]+)", x)).explode()

Assuming you always have the pattern with non digit characters followed by numbers, you can first split and explode joined string into separate rows and then use .str.extract to extract non digit pattern ( \D* ) and number ( \d* ) into different columns:

df['type'].str.split(',').explode().str.extract('(?P<type>\D*)(?P<price>\d*)', expand=True)
  type price
0   gp   250
0   sp   280

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM