Python: How do I split a value in column using regex and keep the right side?

Viewed 173

I'm trying to clean up a column in my data frame that has the count next to size (ex: 12X350). I'm trying to only get the right side of the X which is the size. But having some issues.

import pandas as pd 
data = [['product1', '13X255'], ['product2', "2"], ['product3', "500"]] 
df = pd.DataFrame(data, columns = ['Product', 'Size'])  
df 

    Product     Size
0   product1    13X255
1   product2    2
2   product3    500

Using this string split with regex gets at what I need but fills in values with

df['Size'].str.split(r'[A-Z]', n =1, expand = True)
    0   1
0   13  255
1   2   None
2   500 None

Desired output that I would like to have:

    Product     Size
0   product1    255
1   product2    2
2   product3    500

Any help would be greatly appreciated. Thanks!

2 Answers

Use

df['Right Side Of X'] = df['Size'].str.extract(r'(\d+)$', expand=False).fillna("")

The (\d+)$ expression will capture one or more digits at the end of string. .fillna("") will populate non-matches with empty strings.

IIUC

df['Size'] = df['Size'].str.split(r'[A-Z]', n=1).str[-1]
#if neccessary astype(str)
#df['Size'] = df['Size'].astype(str).str.split(r'[A-Z]', n=1).str[-1]

or

df['Size'] = df['Size'].str.split(r'[A-Z]', n=1, expand = True).ffill(axis=1)[1]

print(df)
    Product Size
0  product1  255
1  product2    2
2  product3  500
Related