Python - Pandas - 只删除只有数字的拆分,但如果它有字母则保持

我有一个具有两个值的数据框:


df = pd.DataFrame({'Col1': ['Table_A112', 'Table_A_112']})

我要做的是在 split('_') 只有数字的情况下删除数字。所需的输出是:


Table_A112

Table_A_

为此,我使用以下代码:


import pandas as pd

import difflib

from tabulate import tabulate

import string


df = pd.DataFrame({'Col1': ['Table_A112', 'Table_A_112']})

print(tabulate(df, headers='keys', tablefmt='psql'))

df['Col2'] = df['Col1'].str.rstrip(string.digits)

print(tabulate(df, headers='keys', tablefmt='psql'))

但它给了我以下输出:


Table_A

Table_A_

怎么能做我想做的事?


谢谢!


开心每一天1111
浏览 132回答 4
4回答

UYOU

这是一种使用方法str.replace:df = pd.DataFrame({'Col1': ['Table_A112', 'Table_A_112', 'Table_112_avs']})print(df)        Col10     Table_A1121    Table_A_1122  Table_112_avsdf.Col1.str.replace(r'(?:^|_)(\d+)(?:$|_)', '_', regex=True)0    Table_A1121      Table_A_2     Table_avsName: Col1, dtype: object

慕哥9229398

如果您坚持使用正则表达式解决方案,您可以使用pandas.replace()并积极向后看r'(?<=_)\d+'import pandas as pdfrom tabulate import tabulatedf = pd.DataFrame({'Col1': ['Table_A112', 'Table_A_112']})print(tabulate(df, headers='keys', tablefmt='psql'))df= df.replace(regex=r'(?<=_)\d+', value='')print(tabulate(df, headers='keys', tablefmt='psql'))这会产生所需的输出。

蓝山帝景

我认为str.replace与捕获组一起使用会使模式更简单sample dfOut[1063]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Col10&nbsp; &nbsp;Table_A1121&nbsp; Table_A_1122&nbsp; Table_111_Bdf.Col1.str.replace(r'(_)\d+', r'\1')Out[1064]:0&nbsp; &nbsp; Table_A1121&nbsp; &nbsp; &nbsp; Table_A_2&nbsp; &nbsp; &nbsp; Table__BName: Col1, dtype: object

慕标琳琳

您可以执行以下操作:s = df['Col1'].str.split('_',expand=True).stack()s.mask(s.str.isdigit(), '').groupby(level=0).agg('_'.join)输出:0&nbsp; &nbsp; Table_A1121&nbsp; &nbsp; &nbsp; Table_A_dtype: object
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python