Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - Replace number-strings with the name ID

Tags:

python

pandas

I have a column in my dataframe of all Strings some of them are TAG(machines/computers), some other items, and the others are ID's. I am looking to change all the strings that are ID's to "ID" instead of the number-string.

type(df.columnOne[1])
str 

This is what my df column looks like:

df
  columnOne
0 TAG
1 1115268
2 13452
3 system
4 TAG
5 355511
6 95221543
7 5124
8 111333544
9 TAG
10 local
11 434312

Desired output:

df
  columnOne
0 TAG
1 ID
2 ID
3 system
4 TAG
5 ID
6 ID
7 ID
8 ID
9 TAG
10 Local
11 ID

I would normally do something where if it doesn't equal TAG or system or Local then ID. But it is always changing with names.

like image 954
sectechguy Avatar asked Dec 11 '22 05:12

sectechguy


2 Answers

If I understand correctly, you can use str.isnumeric:

df.loc[df.columnOne.str.isnumeric(),'columnOne'] = 'ID'

>>> df
   columnOne
0        TAG
1         ID
2         ID
3     system
4        TAG
5         ID
6         ID
7         ID
8         ID
9        TAG
10     local
11        ID
like image 82
sacuL Avatar answered Dec 12 '22 18:12

sacuL


Try replace

df.columnOne = df.columnOne.str.replace('\d+', 'ID')

0        TAG
1         ID
2         ID
3     system
4        TAG
5         ID
6         ID
7         ID
8         ID
9        TAG
10     local
11        ID
like image 24
Vaishali Avatar answered Dec 12 '22 17:12

Vaishali