1. 程式人生 > >pandas 利用 正則表示式 從文字中提取數字

pandas 利用 正則表示式 從文字中提取數字

需要從text特徵中提取形如 13.5/10 這樣的字串,再分別提取分子分母。
1)可以利用 str.extract() 方法。
2)利用正則表示式 \d+\.?\d*\/\d+ 進行匹配
3)再利用 .split() 方法提取分子分母

程式碼:
這裡寫圖片描述

test.text.tolist()

# output
['This is Bella. She hopes her smile made you smile. If not, she is also offering you her favorite monkey. 13.5/10 https://t.co/qjrljjt948',
 "This is Logan, the Chow who lived. He solemnly swears he's up to lots of good. H*ckin magical af 9.75/10 https://t.co/yBO5wuqaPS"
, "This is Sophie. She's a Jubilant Bush Pupper. Super h*ckin rare. Appears at random just to smile at the locals. 11.27/10 would smile back https://t.co/QFaUiIHxHq", 'Here we have uncovered an entire battalion of holiday puppers. Average of 11.26/10 https://t.co/eNm2S6p9BD']
test['rating'] = test['text'].str.extract(r'(\d+\.?\d*\/\d+)'
, expand=False) # 提取分子 test['rating_numerator'] = test.rating.apply(lambda x: eval(x.split('/')[0])) # 提取分母 test['rating_denominator_fix'] = test.rating.apply(lambda x: eval(x.split('/')[1])) # 刪除中間量 test.drop(['rating'], axis=1, inplace=True)

這裡寫圖片描述