4 回答

TA貢獻1878條經驗 獲得超4個贊
這是一種使用方法str.replace:
df = pd.DataFrame({'Col1': ['Table_A112', 'Table_A_112', 'Table_112_avs']})
print(df)
Col1
0 Table_A112
1 Table_A_112
2 Table_112_avs
df.Col1.str.replace(r'(?:^|_)(\d+)(?:$|_)', '_', regex=True)
0 Table_A112
1 Table_A_
2 Table_avs
Name: Col1, dtype: object

TA貢獻1877條經驗 獲得超6個贊
如果您堅持使用正則表達式解決方案,您可以使用pandas.replace()并積極向后看r'(?<=_)\d+'
import pandas as pd
from tabulate import tabulate
df = 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'))
這會產生所需的輸出。

TA貢獻1843條經驗 獲得超7個贊
我認為str.replace與捕獲組一起使用會使模式更簡單
sample df
Out[1063]:
Col1
0 Table_A112
1 Table_A_112
2 Table_111_B
df.Col1.str.replace(r'(_)\d+', r'\1')
Out[1064]:
0 Table_A112
1 Table_A_
2 Table__B
Name: Col1, dtype: object

TA貢獻1830條經驗 獲得超9個贊
您可以執行以下操作:
s = df['Col1'].str.split('_',expand=True).stack()
s.mask(s.str.isdigit(), '').groupby(level=0).agg('_'.join)
輸出:
0 Table_A112
1 Table_A_
dtype: object
添加回答
舉報