简体   繁体   English

如何从文本文件中的列中读取数据到 python 中的 3 1D numpy arrays

[英]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.

相关问题 Python / Numpy-将多个一维数组写入整齐的列中的文件 - Python/Numpy - writing multiple 1D arrays to a file in neat columns 如何将文本文件中的一维数据读入一维数组? [Python] - How do I read 1 dimensional data from a text file into a 1D array? [Python] 如何在numpy中遍历一维和二维数组的列? - How to iterate over columns of 1D an 2D arrays in numpy? Python numpy - DepricationWarning:不推荐使用1d数组作为数据 - Python numpy - DepricationWarning: Passing 1d arrays as data is deprecated 在Python中过滤一维numpy数组 - Filtering 1D numpy arrays in Python 如何在不复制的情况下从单个 1D Numpy 数组构造 Pandas DataFrame - How can I construct a Pandas DataFrame from individual 1D Numpy arrays without copying 如何通过添加 1d numpy ZA3CCBC3F9D0CE2D71D1555 从空的 numpy 数组制作 2d numpy 数组 - How to make a 2d numpy array from an empty numpy array by adding 1d numpy arrays? 您可以使用 3 个单独的 1D numpy arrays 来使用矢量化操作 3D 数组吗? - Can you use 3 seperate 1D numpy arrays to manipulate a 3D array using vectorization? 如何在 NumPy 中叠加两个 1d arrays? - How to overlay two 1d arrays in NumPy? numpy数组而不是python列表-使用nditer从两个1d数组创建2d数组 - Numpy arrays instead of python lists - using nditer to create a 2d array from two 1d arrays
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM