[英]How do i store values from a text file into a 2D Numpy array?
I have a dataset on a txt file with 373 rows and 3 columns.My teacher asked me to create 2 arrays.The 'array1' stores all the rows of the dataset that their third column has the value 1,and the 'array2' stores every row that has number 2 at column2.我有一个 txt 文件的数据集,有 373 行和 3 列。我的老师让我创建 2 个 arrays。“array1”存储数据集的所有行,它们的第三列值为 1,“array2”存储在第 2 列有数字 2 的每一行。 The arrays must be numpy arrays.
arrays 必须是 numpy arrays。 I tried 'class1 = np.zeros(len(dataset)).reshape(len(dataset)//3,3)' but i was getting the error message: 'ValueError: cannot reshape array of size 373 into shape (124,3)' I tried all different kinds of variations.
我试过 'class1 = np.zeros(len(dataset)).reshape(len(dataset)//3,3)' 但我收到错误消息:'ValueError: cannot reshape array of size 373 into shape (124, 3)'我尝试了各种不同的变化。 But i couldnt find a way to make a 2D work.I only managed to store the column number1 with on both arrays with this code:
但我无法找到一种方法来进行 2D 工作。我只能使用以下代码在 arrays 上存储列 number1:
'''
import numpy as np
dataset = np.loadtxt("first_attempt_dataset.txt")
class1 = np.zeros(len(dataset))
class2 = np.zeros(len(dataset))
for i in range(0,len(dataset)):
if dataset[i,2] == 1:
class1[i] = dataset[i][1]
elif dataset[i,2] == 2:
class2[i] = dataset[i][1]
class1 = class1[class1 != 0] #delete the remained zeros from declaration
class2 = class2[class2 != 0]
'''
How can i store every column instead of only 1?我如何存储每一列而不是仅存储 1 列?
I feel you misunderstand the question from your teacher.我觉得你误解了老师的问题。 The question is "...The 'array1' stores all the rows of the dataset that their third column has the value 1,...", so I would do this:
问题是“......'array1'存储数据集的所有行,它们的第三列的值为1,......”,所以我会这样做:
import numpy as np
a = np.array([[1,2,3], [3,2,1], [2,3,1], [2,1,3], [3,1,2]])
b = a[a[:,2]==1]
print(b)
result is:结果是:
[[3 2 1]
[2 3 1]]
Similar to the second half of the question, you need to change the column number to 1
.与问题的后半部分类似,您需要将列号更改为
1
。
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.