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?
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 '.
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.
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.
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") .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With