0

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)
4
  • Please show what you have tried? Commented Oct 16, 2014 at 9:18
  • Please add your code to do the question, not in a comment. Commented Oct 16, 2014 at 9:21
  • Use a dictionary d = {'first': 1, 'second': 2}. Than you can say d['first'] which will retun 1 Commented Oct 16, 2014 at 9:21
  • how would I convert a dataset of strings to a dictionary? Commented Oct 16, 2014 at 9:22

3 Answers 3

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')
Sign up to request clarification or add additional context in comments.

Comments

0

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

so i have a dataset where the first line is "third, adult, male, yes" second line is "second, adult, female, yes", etc. I want third to equal the same int value throughout,and so on.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.