I have a dataframe that look like this:
from pyspark.sql.functions import *
from pyspark.sql.types import *
data = [('1',"12345 soda bottle 1500ml"),\
('2',"6789 beer can 450ml"),\
("3","beer with no number before 375ml")\
]
columnname = ['id','product']
df = spark.createDataFrame(data=data, schema = columnname)
+---+--------------------------------+
|id |product |
+---+--------------------------------+
|1 |12345 soda bottle 1500ml |
|2 |6789 beer can 450ml |
|3 |beer with no number before 375ml|
+---+--------------------------------+
I want the volume in another column, but some of the values has numbers that I don't need.
So far I tried this:
df = df.withColumn('volume',regexp_extract(col('product'), '([0-9]{3,5}.*ml)', 1)
).withColumn('volume_number',regexp_extract(col('volume'), '^[^m]+', 0))
But the result is not what I spected:
+---+--------------------------------+------------------------+----------------------+
|id |product |volume |volume_number |
+---+--------------------------------+------------------------+----------------------+
|1 |12345 soda bottle 1500ml |12345 soda bottle 1500ml|12345 soda bottle 1500|
|2 |6789 beer can 450ml |6789 beer can 450ml |6789 beer can 450 |
|3 |beer with no number before 375ml|375ml |375 |
+---+--------------------------------+------------------------+----------------------+
Desired output:
+---+--------------------------------+------------------------+----------------------+
|id |product |volume |volume_number |
+---+--------------------------------+------------------------+----------------------+
|1 |12345 soda bottle 1500ml |1500ml |1500 |
|2 |6789 beer can 450ml |450ml |450 |
|3 |beer with no number before 375ml|375ml |375 |
+---+--------------------------------+------------------------+----------------------+