0

I am importing a csv file into python. As expected, it creates lists with every value as a string, however I want to avoid this. Is there a way for python to detect that a value is actually an int even though it looks like this '24'?

Thank you.

martineau
  • 119,623
  • 25
  • 170
  • 301
plshelp
  • 243
  • 1
  • 3
  • 12

3 Answers3

1

You may want to write a function something like this to do the job. You can expand it to cover other data type.

def return_str_type(str):
    possible_type = [int, float]
    for dtype in possible_type:
        try:
            str = dtype(str)
            break   
        except:
            pass
    return type(str).__name__

print(return_str_type('4'))
print(return_str_type('4.3'))
print(return_str_type('s4'))

This will give OP

int
float
str

Though you will have to be careful with the order. e.g. int check should always be before float.

saurabh baid
  • 1,819
  • 1
  • 14
  • 26
  • you don't need eval for this, make a list with the classes and do `str=dtype(str)` – Copperfield Nov 05 '16 at 15:29
  • updated as per you suggestion @Copperfield – saurabh baid Nov 05 '16 at 15:33
  • You beat me to it. I had the same except the function excepted a complete row and returned a list of converted items. Used with ```data = map(f, csv.reader)``` – wwii Nov 05 '16 at 15:36
  • @saurabhbaid I think you're onto something! I managed to get a whole list of str and int. Thanks so much! – plshelp Nov 05 '16 at 15:45
  • 1
    As your example shows, there's a built-in type name `str`, so it's best to avoid defining your own variable, arguments, etc, the same. – martineau Nov 05 '16 at 16:59
0

ast.literal_eval is what you seek.

print ast.literal_eval('[1, 2, 3]') == [1, 2, 3]
print ast.literal_eval('23') == 23

Python also has an eval command, however it is not safe because non-datatype commands can also be processed for harmful purposes through this function.

Rockybilly
  • 2,938
  • 1
  • 13
  • 38
-1

A number of various modules supports this, pandas among them. read_csv can infer the data types.

Lukasz Tracewski
  • 10,794
  • 3
  • 34
  • 53