How to read tsv into int np array in Collaboratory

Viewed 72

I have a text file consisting of

1 0 0 1
1 1 1 1
1 1 1 0
1 0 1 0
0 0 0 1

. I need it as integer array

np.array([  
  [1, 0, 0, 1]  
  [1, 1, 1, 1]  
  [1, 1, 1, 0]   
  [1, 0, 1, 0]  
  [0, 0, 0, 1]  
])

in Google Collab.

If I do

from google.colab import files
import pandas as pd
import numpy as np

uploaded = files.upload()
data = pd.read_table('filename.txt')
np_arr = np.array(data)

, I get

[  
  ['1 0 0 1']  
  ['1 1 1 1']  
  ['1 1 1 0']   
  ['1 0 1 0']  
  ['0 0 0 1']  
]

.

I couldn't use dtype=int to change those strings to integers. Does annyone know how to do this? Furthermore, I did it in the past without stating the actual filename, just using a dummy name and could therefore read new files without changing code (in Google Collab). Annyone aware of that possibility?

0 Answers
Related