Finkployd
Finkployd

Reputation: 11

Convert a text file to an numpyarray

I am new to python. I have a .txt file

SET = 20,21,23,21,23 
      45,46,42,23,55

with many number of rows. How would I convert this txt file into an array ignoring spaces and commas? Any help would be really appreciated.

Upvotes: 1

Views: 62

Answers (2)

Essex
Essex

Reputation: 6138

Your data looks like :

SET 1 = 13900100,13900141,13900306,13900442,13900453,13900461, 13900524,13900537,13900619,13900632,13900638,13900661, 13900665,13900758,13900766,13900825,13900964,13901123, 13901131,13901136,13901141,13901143,13901195,13901218,

you can use the numpy command : np.genfromtxt ()

import numpy as np
import matplotlib.pyplot as plt

data = np.genfromtxt("text.txt", delimiter=",")

data = data[np.logical_not(np.isnan(data))] #Remove nan value

print data

I get :

[ 13900141.  13900306.  13900442.  13900453.  13900461.  13900524.
  13900537.  13900619.  13900632.  13900638.  13900661.  13900665.
  13900758.  13900766.  13900825.  13900964.  13901123.  13901131.
  13901136.  13901141.  13901143.  13901195.  13901218.]

It should work ;)

------------------------------------

Other way :

import numpy as np

f = open("text.txt", "r") #Open data file
data = f.read() #Read data file

cut = data.split() #Split data file

value = cut[2] #Pick the value part

array = np.array(value) #Value becomes an array

print array

I get :

13900100,13900141,13900306,13900442,13900453,13900461,13900524,13900537,13900619,13900632,13900638,13900661,13900665,13900758,13900766,13900825,13900964,13901123,13901131,13901136,13901141,13901143,13901195,13901218

Upvotes: 1

Suraj
Suraj

Reputation: 178

l1=[]
file = open('list-num')
for l in file:
    l2 = map(int,l.split(','))
    l1 = l1 + l2 
print l1

Upvotes: 1

Related Questions