首页 > 解决方案 > 如何在 Collaboratory 中将 tsv 读入 int np 数组

问题描述

我有一个文本文件,由

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

. 我需要它作为整数数组

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

在 Google 协作中。

如果我做

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)

,我得到

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

.

我不能dtype=int用来将这些字符串更改为整数。有人知道该怎么做吗?此外,我过去在没有说明实际文件名的情况下这样做,只是使用了一个虚拟名称,因此可以在不更改代码的情况下读取新文件(在 Google Collab 中)。有人知道这种可能性吗?

标签: pythonnumpyintegerreadfile

解决方案


推荐阅读