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.
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.
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
.
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.
A number of various modules supports this, pandas among them. read_csv
can infer the data types.