Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I want to replace the string value in the Python list with a specific number value. For example:

l = ["orange", "lemon", "apple", "orange", "apple","orange", "lemon","lemon", "apple", "grape", "grape", "lemon", "grape"]

I want to get:

l = [1, 2, 3, 1, 3, 2, 2, 3, 4, 4, 2, 4]

I know that it can be done using the pandas and map functions. But what if I have 50 different categories? It would be stupid to write a different case for each category? Is there the way to do this automatically?

1 Answer

0 votes
by (36.8k points)

Probably impractical, but you can use a id of each string:

l = ["orange", "lemon", "apple", "orange", "apple"]

l2 = [id(s) for s in l]

print(l2)

Output:

[2379879963760, 2379879963504, 2379877859760, 2379879963760, 2379877859760]

Every unique string will have the unique id.

Want to be a master in Data Science? Enroll in this Data Science Courses

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...