Py学习  »  Python

Python:如何使用regex拆分列中的值并保留右边?

Sizzling_Boots • 3 年前 • 555 次点击  

我试图清理数据帧中的一列,该列的计数与size(例如:12X350)相邻。我只想得到X的右边,也就是这个尺寸。但是有些问题。

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

在regex中使用这个字符串分割可以得到我需要的结果,但是用

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

我想要的输出:

    Product     Size
0   product1    255
1   product2    2
2   product3    500

任何帮助都将不胜感激。谢谢!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/99358
 
555 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Ryszard Czech
Reply   •   1 楼
Ryszard Czech    3 年前

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

这个 (\d+)$ 表达式将在字符串末尾捕获一个或多个数字。 .fillna("") 将用空字符串填充非匹配项。

ansev
Reply   •   2 楼
ansev    3 年前

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]

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