Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Can someone help on that?

like image 399
aabujamra Avatar asked May 05 '18 16:05

aabujamra


People also ask

How do you check if a column has numeric values in pandas?

Pandas str. isdigit() method is used to check if all characters in each string in series are digits. Whitespace or any other character occurrence in the string would return false. If the number is in decimal, then also false will be returned since this is a string method and '.

How do you check if a column has characters in pandas?

Pandas str. isalpha() method is used to check if all characters in each string in series are alphabetic(a-z/A-Z). Whitespace or any other character occurrence in the string would return false, but if there is a complete numeric value, then it would return NaN.

How do you check alphanumeric pandas?

isalnum() Function in python checks whether the string consists of alphanumeric characters. It returns True when alphanumeric value is present and it returns False when the alphanumeric value is not present.

How do you check if a string contains a character pandas?

Using “contains” to Find a Substring in a Pandas DataFrame The contains method returns boolean values for the Series with True for if the original Series value contains the substring and False if not. A basic application of contains should look like Series. str. contains("substring") .


1 Answers

You are close. The trick is to use the .str accessor via pd.Series.str.isnumeric.

Then map to 'A' or an empty string via pd.Series.map:

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     
like image 171
jpp Avatar answered Oct 01 '22 14:10

jpp