-1

My Dataframe enter image description here

My code-

for x in df.ROAD_NAME_NUMBER:
    if int(x) == x:
        df.ROAD_NAME_NUMBER= 'Road '+ df.ROAD_NAME_NUMBER

I getting the error- ValueError: invalid literal for int() with base 10: 'Avenue 5, Lane 23'

My expected dataframe should look like this - enter image description here

When any integer will be found in dataframe add "Road" before it.Otherwise ignore.


import pandas a pd
df = pd.DataFrame({'ROAD_NAME_NUMBER':['4','2','1','8','2','AVE 5,LANE 2']})

>>> print(df)
  ROAD_NAME_NUMBER
0                4
1                2
2                1
3                8
4                2
5     AVE 5,LANE 2
wwii
  • 23,232
  • 7
  • 37
  • 77
bellatrix
  • 139
  • 9
  • 1
    Please don't post images of code, data, or Tracebacks. [Discourage screenshots of code and/or errors](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors)...[Why not upload images of code on SO when asking a question?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question) ... [You should not post code as an image because:...](https://meta.stackoverflow.com/a/285557/2823755) ... – wwii Sep 10 '21 at 13:41
  • [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – wwii Sep 10 '21 at 13:41

3 Answers3

2

Assuming that the ROAD_NAME_NUMBER column be text, you could try using str.replace here:

df["ROAD_NAME_NUMBER"] = df["ROAD_NAME_NUMBER"].str.replace(r'^(\d+)$', r'Road \1')
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

You should try using something like this:

df = df.applymap(lambda x: 'Road ' + x['ROAD_NAME_NUMBER'] if type(x['ROAD_NAME_NUMBER']) == int else x['ROAD_NAME_NUMBER'])
GabrielBoehme
  • 302
  • 1
  • 11
1

It is advisable not to iterate over DataFrame columns as you've tried. This should work in your case:

df.loc[df.ROAD_NAME_NUMBER.astype(str).str.isdigit(), 'ROAD_NAME_NUMBER'] = "Road " + df.ROAD_NAME_NUMBER.astype(str)
Shivam Roy
  • 1,961
  • 3
  • 10
  • 23