亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python - Pandas - 只刪除只有數字的拆分,但如果它有字母則保持

Python - Pandas - 只刪除只有數字的拆分,但如果它有字母則保持

開心每一天1111 2022-07-26 09:27:26
我有一個具有兩個值的數據框:df = pd.DataFrame({'Col1': ['Table_A112', 'Table_A_112']})我要做的是在 split('_') 只有數字的情況下刪除數字。所需的輸出是:Table_A112Table_A_為此,我使用以下代碼:import pandas as pdimport difflibfrom tabulate import tabulateimport stringdf = 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_ATable_A_怎么能做我想做的事?謝謝!
查看完整描述

4 回答

?
UYOU

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


查看完整回答
反對 回復 2022-07-26
?
慕哥9229398

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'))

這會產生所需的輸出。


查看完整回答
反對 回復 2022-07-26
?
藍山帝景

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


查看完整回答
反對 回復 2022-07-26
?
慕標琳琳

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


查看完整回答
反對 回復 2022-07-26
  • 4 回答
  • 0 關注
  • 105 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號