The Python Oracle

In Python Pandas, how to search if column elements contains the first 2 digits

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Jungle Looping

--

Chapters
00:00 In Python Pandas, How To Search If Column Elements Contains The First 2 Digits
01:01 Answer 1 Score 1
01:14 Accepted Answer Score 2
01:40 Answer 3 Score 2
01:59 Answer 4 Score 2
02:20 Thank you

--

Full question
https://stackoverflow.com/questions/5251...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pandas

#avk47



ACCEPTED ANSWER

Score 2


I tried this df.loc[df.AreaCode.str.contains == 12, 'Region' ] = 'A' but it gives me the error: AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

You could simply convert it to a string, then use the same code:

df.loc[df.AreaCode.astype(str).str.startswith('12'), 'Region' ] = 'A'



ANSWER 2

Score 2


Try this

df.loc[df.AreaCode.astype(str).str.startswith("12") == True, 'Region' ]

The line below will give you a series with True/False for each row and what becomes the filter for the dataframe.

df.AreaCode.astype(str).str.startswith("12")

Assigning a equals test makes it a filter.




ANSWER 3

Score 2


See if this helps -

First convert Area code column dtype to string with

df.AreaCode = df.AreaCode.astype(str)

And then do filtering with first characters of the column

df.loc[(df.AreaCode.str.startswith('12')) & (df.Region=='A')]




ANSWER 4

Score 1


This will work I guess.

df.loc[df.AreaCode.str.startswith('12'), 'Region' ] = 'A'