Landon G
Landon G

Reputation: 839

Loading txt file data into a numpy array / getting an error

I'm trying to load a txt file data into a numpy array. It's throwing the following error:

ValueError: could not convert string to float: '6,50,36'

The txt file I am trying to upload into the array is this (this is the full file):

6,50,36
2,0,1,3,0,1
1,2,1,2,1,2
2,1,2,1,0,1
0,2,0,2,2,3
0,3,3,3,1,4
2,3,2,3,1,3

I've did some research and thought that the "np.loadtxt()" would be an easy solution to load this txt into an array, so this is what I've tried so far:

import numpy as np
from numpy import loadtxt

f = open('DataNumbers.txt','r')
data_array = float(np.loadtxt(f))  # I thought using 'float' would work for this issue

I'm wondering if the reason this isn't working is because the file contains two blank spaces after 36 on the first line of the txt file?

How can I get this data from the txt file loaded into an array and get rid of this error?

Thanks for your help!

Upvotes: 1

Views: 1236

Answers (1)

hpaulj
hpaulj

Reputation: 231738

In [498]: f = open('stack53641413.txt','r')
In [501]: alist = [[int(x) for x in line.split(',')] for line in f]
In [502]: alist
Out[502]: 
[[6, 50, 36],
 [2, 0, 1, 3, 0, 1],
 [1, 2, 1, 2, 1, 2],
 [2, 1, 2, 1, 0, 1],
 [0, 2, 0, 2, 2, 3],
 [0, 3, 3, 3, 1, 4],
 [2, 3, 2, 3, 1, 3]]
In [504]: np.array(alist[1:])
Out[504]: 
array([[2, 0, 1, 3, 0, 1],
       [1, 2, 1, 2, 1, 2],
       [2, 1, 2, 1, 0, 1],
       [0, 2, 0, 2, 2, 3],
       [0, 3, 3, 3, 1, 4],
       [2, 3, 2, 3, 1, 3]])

What you do with alist[0] is your business.

loadtxt skipping the difficult first line:

In [507]: np.loadtxt(f, dtype='int', delimiter=',',skiprows=1)
Out[507]: 
array([[2, 0, 1, 3, 0, 1],
       [1, 2, 1, 2, 1, 2],
       [2, 1, 2, 1, 0, 1],
       [0, 2, 0, 2, 2, 3],
       [0, 3, 3, 3, 1, 4],
       [2, 3, 2, 3, 1, 3]])

Upvotes: 1

Related Questions