Skip to content Skip to sidebar Skip to footer

Read Csv Data As Integer In Python

I have ancsv file with the data in the following format 1,F,1,10,48067 2,M,56,16,70072 3,M,25,15,55117 4,M,45,7,02460 5,M,25,20,55455 6,F,50,9,55117 7,M,35,1,06810 8,M,25,12,11413

Solution 1:

Something like this:

import csv

result= list()
withopen('filepath.csv') as f:
    reader = csv.reader(f)
    forrowin reader:
        result.append(list())
        for item inrow:
            if item =='F'result[-1].append(0)
            elif item =='M':
                result[-1].append(1)
            else:
                result[-1].append(item)  

Here is a shorter and a beautiful solution:

import csv

result= list()
withopen('filepath.csv') as f:
    reader = csv.reader(f)
    forrowin reader:
        result.append([i if (i!='F'and i!='M') else (0 if i=='F'else1) for i inrow])

Note that I didn't test the code. I just blindly wrote it here directly.

Post a Comment for "Read Csv Data As Integer In Python"