简体   繁体   English

来自python中带列文本文件的2D数组

[英]2D Array from a columned text file in python

I am new to python and working on a script that will create a 2D array from a text file. 我是python的新手,正在研究一个将从文本文件创建2D数组的脚本。 The file has 4 columns, like so: 该文件有4列,如下所示:

P    F    T    S
0    0    0    0.227321
0    0    1    0.0380602
0    0    2    -0.804958
0    0    3    0.271401

Where P, F, T, and S are the polarization state, frequency, time, and signal strength, respectively. 其中P,F,T和S分别是极化状态,频率,时间和信号强度。 I want to create a 2D matrix of S such that they will have x and y coordinates of the corresponding T and F values (Ignoring P). 我想创建一个S的2D矩阵,这样它们将具有相应T和F值的X和Y坐标(忽略P)。 I know how to create a matrix from text, but that just creates a 4 by n matrix that is identical in form to the text file. 我知道如何从文本创建矩阵,但是仅创建一个4×n矩阵,其形式与文本文件相同。 How can I generate the 2D matrix I need? 如何生成所需的2D矩阵?

EDIT: I meant ignoring P, not S. 编辑:我的意思是忽略P,而不是S。

Suppose your text file is named data.txt 假设您的文本文件名为data.txt

import numpy as np
dat = np.loadtxt( 'data.txt' )

now dat[0,:] will be the first row and dat[:,2] will be the third column and so on. 现在dat[0,:]将成为第一行,而dat[:,2]将成为第三列,依此类推。 Note that you will have to add a comment character to the first line # of your file so it wont be readin by loadtxt . 请注意,您将有一个注释字符添加到第一行#你的文件,因此它不会是阅读下载的loadtxt

ii = dat[:,1].astype( np.int )  # this is the F column as ints
jj = dat[:,2].astype( np.int )  # this is the T column as ints

nx = max(ii) + 1
ny = max(jj) + 1
d = np.zeros( (nx,ny) )

n = 0
for i,j in zip(ii,jj):
    d[i,j] = dat[n,3]
    n += 1

Now d will have the values of S in the locations specified by the columns F and T and 0's elsewhere. 现在dFT列指定的位置具有S的值,而在其他位置为0。

How about this sample: 该示例如何:

with open("matrix.txt", "r") as df:
    txt = df.read()
    items = txt.split()
    items = [float(n) for n in items]
    data = zip([i for i in items[1::4]], [i for i in items[2::4]], [i for i in items[3::4]])
    print(data)
    print(data[1][2])

Output: 输出:

[(0.0, 0.0), (0.0, 1.0), (0.0, 2.0), (0.0, 3.0)] [(0.0,0.0),(0.0,1.0),(0.0,2.0),(0.0,3.0)]

1.0 1.0

"data" now includes X y coordinates and the value. 现在,“数据”包括X y坐标和值。 you should have all you need 你应该拥有所需的一切

  1. Read in the file and save all of the data into a 4 by n matrix as you said. 如您所说,读入文件并将所有数据保存到4 x n矩阵中。
  2. Then loop through each row and save the appropriate S or P value as array[F][T]=S 然后遍历每一行,并将适当的S或P值保存为array [F] [T] = S

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM