简体   繁体   English

检查字符串列的最后一个字符是否是Pandas中的数字

[英]Check if string column last characters are numbers in Pandas

I have this dataframe: 我有这个数据帧:

   Code               Mark
0  Abd 43212312312   
1  Charles de Gaulle
2  Carlitos 4132411  
3  Antonio

If the last 5 characters of the string in the Code column are numbers, I want that 'Mark' is 'A', so it will look like this: 如果Code列中字符串的最后5个字符是数字,我希望'Mark'是'A',所以它看起来像这样:

   Code               Mark
0  Abd 43212312312    A
1  Charles de Gaulle
2  Carlitos 4132411   A
3  Antonio

I'm trying to use isnumeric but I'm constantly getting AttributeError: 'Series' object has no attribute 'isnumeric' 我正在尝试使用isnumeric,但我经常遇到AttributeError: 'Series' object has no attribute 'isnumeric'

Can someone help on that? 有人可以帮忙吗?

You are close. 你很亲密 The trick is to use the .str accessor via pd.Series.str.isnumeric . 诀窍是通过pd.Series.str.isnumeric使用.str访问pd.Series.str.isnumeric

Then map to 'A' or an empty string via pd.Series.map : 然后通过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     

Using pd.Series.str.match , you can use 使用pd.Series.str.match ,您可以使用

import numpy as np

df['Mark'] = np.where(df.Code.str.match(r'.*?\d{5}$'), 'A', '')

Note that '.*? 请注意'.*? ' is a non-greedy regex match, '\\d{5}' checks for 5 digits, and '$' matches a string end. '是非贪婪的正则表达式匹配, '\\d{5}'检查5位数, '$'匹配字符串结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python - 检查字符串中的最后一个字符是否为数字 - Python - Check if the last characters in a string are numbers 如何检查字符串的最后一个字符 - how to check last characters of a string 熊猫 - 检查列中的数字是否在行中 - Pandas - Check if Numbers in Column are in row 对 Pandas 列中的一串数字进行排序 - Sort a String of Numbers in a Pandas Column Pandas df - 如果最后一列为空,则复制最后一列可能的数字 - Pandas df - copy the last possible column with numbers if the last column is empty 检查包含数字的列中是否有字符串 - Check if there a string in a column containing numbers 检查字符串是否在另一列熊猫中 - Check if string is in another column pandas Pandas DataFrame:如何从并非总是以两个数字结尾的列中提取最后两个字符串类型的数字 - Pandas DataFrame: How to extract the last two string type numbers from a column which doesn't always end with the two numbers 在Pandas中,如何检查三个组合的字符串列是否== 10个字符,如果是,则插入新列? - In Pandas, how do I check if three combined string columns == 10 characters, and if so, insert into new column? 取得一列对象的最后一个字符并使其成为数据框上的列-Pandas Python - Taking last characters of a column of objects and making it the column on a dataframe - pandas python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM