[英]How can you read data from columns in a text file into 3 1D numpy arrays in python
I have data in a text file with 3 columns and 4 rows like this:我在一个包含 3 列和 4 行的文本文件中有数据,如下所示:
5 6.4 17
6 5.8 16
7 5.5 3.9
8 5.3 10.4
I want to read this data from the text file into 3 1D arrays each with 4 elements我想将文本文件中的这些数据读入 3 个 1D arrays 每个有 4 个元素
I have this code:我有这个代码:
import numpy as np with open('data.txt','rt') as filedata: values=np.genfromtxt('data.txt', unpack=True)
this has created a 2D (3,4) array.这创建了一个 2D (3,4) 数组。 I managed to split it into 3 subarrays using np.slice(values,4)
but then I didn't know how to rename and subsequently use those subarrays我设法使用np.slice(values,4)
将其拆分为 3 个子数组,但后来我不知道如何重命名并随后使用这些子数组
You can use python's slice notation:您可以使用 python 的切片表示法:
import numpy as np
with open('data.txt','rt') as filedata:
values = np.genfromtxt('data.txt', unpack=True)
array1 = values[:, 0]
array2 = values[:, 1]
array3 = values[:, 2]
When you use slicing the first value defines the range in rows and the second in columns.当您使用切片时,第一个值定义行中的范围和列中的第二个值。 So by typing values[:, 0]
you say give me all elements in 0th column.所以通过输入values[:, 0]
你说给我第 0 列中的所有元素。 The semicolon lets you specify a range.分号可让您指定范围。 For example, values[0:2, 0]
says give me the first two elements in the 0th column.例如, values[0:2, 0]
表示给我第 0 列的前两个元素。 You can look at the slicing notation in more detail here .您可以在此处更详细地查看切片符号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.