I want to convert a string to a specific int value in Python i.e. "red" I want to be 1, "blue" to 2, etc. I am currently using if-else statements. I have a dataset of strings with common strings that I want to associate with a number. Please help.
def discretize_class(x):
if x == 'first':
return int(1)
elif x == 'second':
return int(2)
elif x == 'third':
return int(3)
elif x == 'crew':
return int(4)
-
Please show what you have tried?Vishnu Upadhyay– Vishnu Upadhyay2014年10月16日 09:18:44 +00:00Commented Oct 16, 2014 at 9:18
-
Please add your code to do the question, not in a comment.Ffisegydd– Ffisegydd2014年10月16日 09:21:23 +00:00Commented Oct 16, 2014 at 9:21
-
Use a dictionary d = {'first': 1, 'second': 2}. Than you can say d['first'] which will retun 1Vincent Beltman– Vincent Beltman2014年10月16日 09:21:25 +00:00Commented Oct 16, 2014 at 9:21
-
how would I convert a dataset of strings to a dictionary?user3318660– user33186602014年10月16日 09:22:09 +00:00Commented Oct 16, 2014 at 9:22
3 Answers 3
You need to use a dictionary. That would be best I think:
dictionary = {'red': 1, 'blue': 2}
print dictionary['red']
Or with the new code you added just now:
def discretize_class(x):
dictionary = {'first': 1, 'second': 2, 'third': 3, 'crew': 4}
return dictionary[x]
print discretize_class('second')
Comments
Assuming, by datasets, you either mean a
- text file
- database table
- a list of strings
So first thing importantly, you need to know, how you can read the data. Example for
- test file: You can simply read the file and iterate through the file object
- database table: Based on what library you use, it would provide an API to read all the data into a list of string
- list of strings: Well you already got it
Enumerate all the strings using the built-in enumerate
Swap the enumeration with the string
Either use dict-comprehension (if your python version supports), or convert the list of tuples to a dictionary via the built-in `dict
with open("dataset") as fin:
mapping = {value: num for num, value in enumerate(fin)}
This will provide a dictionary, where each string, ex, red or blue is mapped to a unique number
1 Comment
Your question is a bit vague, but maybe this helps.
common_strings = ["red","blue","darkorange"]
c = {}
a = 0
for item in common_strings:
a += 1
c[item] = a
# now you have a dict with a common string each with it's own number.