Skip to content Skip to sidebar Skip to footer

How To Convert String Datatypes To Float In Numpy Arrays In Python 3

I have been using Python 2.7 for some time now and have recently switched to Python 3. I have already updated my code on some points, but the problem I currently have deludes me. W

Solution 1:

As suggested by dnalow, something goes wrong in the type conversion because I first open the file and then read from it. The solution is to not use open open(filename, 'rb') and np.loadtxt, but to use np.genfromtxt. Code below.

    filename = 'train.csv'
    data = np.genfromtxt(filename, delimiter=",", dtype = 'str')
    dataset = data[1:,1:]
    print(dataset)
    original_data = dataset
    test = float(dataset[0,0])
    print(test)
    filename = 'train.csv'
    data = np.genfromtxt(filename, delimiter=",", dtype = 'str')
    dataset = data[1:,1:]
    print(dataset)
    original_data = dataset
    test = float(dataset[0,0])
    print(test)

Result

[['60''RL''65' ..., 'WD''Normal''208500']['20''RL''80' ..., 'WD''Normal''181500']['60''RL''68' ..., 'WD''Normal''223500']
     ..., 
     ['70''RL''66' ..., 'WD''Normal''266500']['20''RL''68' ..., 'WD''Normal''142125']['20''RL''75' ..., 'WD''Normal''147500']]
    60.0

Post a Comment for "How To Convert String Datatypes To Float In Numpy Arrays In Python 3"