[英]Check if string column last characters are numbers in Pandas
我有這個數據幀:
Code Mark
0 Abd 43212312312
1 Charles de Gaulle
2 Carlitos 4132411
3 Antonio
如果Code列中字符串的最后5個字符是數字,我希望'Mark'是'A',所以它看起來像這樣:
Code Mark
0 Abd 43212312312 A
1 Charles de Gaulle
2 Carlitos 4132411 A
3 Antonio
我正在嘗試使用isnumeric,但我經常遇到AttributeError: 'Series' object has no attribute 'isnumeric'
有人可以幫忙嗎?
你很親密 訣竅是通過pd.Series.str.isnumeric
使用.str
訪問pd.Series.str.isnumeric
。
然后通過pd.Series.map
映射到'A'或空字符串:
df['Mark'] = df['Code'].str[-5:]\
.str.isnumeric()\
.map({True: 'A', False: ''})
print(df)
Code Mark
0 Abd43212312312 A
1 CharlesdeGaulle
2 Carlitos4132411 A
3 Antonio
使用pd.Series.str.match
,您可以使用
import numpy as np
df['Mark'] = np.where(df.Code.str.match(r'.*?\d{5}$'), 'A', '')
請注意'.*?
'是非貪婪的正則表達式匹配, '\\d{5}'
檢查5位數, '$'
匹配字符串結尾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.