Python的 - 从创建文件列数组 [英] Python - Create an array from columns in file

查看:145
本文介绍了Python的 - 从创建文件列数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两列和n行的文本文件。通常我使用两个单独的vector X,Y = np.loadtxt工作(数据,usecols =(0,1),解压= TRUE),但我想它们作为形式数组的数组= [[A,1],[b,2],[C,3] ...] ,所有的字母对应于x矢量和号码的y矢量,所以我可以问类似数组[0,2] = b 。我试图定义
数组[0:] = X ,但我没有成功。任何简单的方法来做到这一点?

I have a text file with two columns and n rows. Usually I work with two separate vector using x,y=np.loadtxt('data',usecols=(0,1),unpack=True) but I would like to have them as an array of the form array=[[a,1],[b,2],[c,3]...] where all the letters correspond to the x-vector and the numbers to the y-vector so I can ask something like array[0,2]=b. I tried defining array[0,:]=x but I didn't succeed. Any simple way to do this?

另外,我想对某些y值相应的X值。我试着用

In addition, I want to get the respective x-value for certain y-value. I tried with

x_value=np.argwhere(array[:,1]==3)

和我期待的X_VALUE为c,因为它对应于3列1,但它不工作的。

And I'm expecting the x_value to be c because it corresponds to 3 in column 1 but it doesn't work either.

推荐答案

我觉得你只需要解压不是你从 loadtxt 回阵列。这样做:

I think you simply need to not unpack the array you get back from loadtxt. Do:

arr = np.loadtxt('data', usecols=(0,1))

如果您的文件包含:

0 1
2 3
4 5

改编将是这样的:

[[0, 1],
 [2, 3],
 [4, 5]]

请注意,要索引这个数组,你需要先指定行(和索引从0开始):

Note that to index into this array, you need to specify the row first (and indexes start at 0):

arr[1,0] == 2 # True!

您可以找到 X 对应于一个给值和值:

You can find the x values that correspond to a give y value with:

x_vals = arr[:,0][arr[:,1]==y_val]

该索引将返回一个数组,但 x_vals 将只有一个值,如果 y_val 是独一无二的。如果事先知道将只有一个为 y_val ,你可以钉在 [0] 来比赛索引的结束,所以你得到的第一个结果。

The indexing will return an array, though x_vals will have only a single value if the y_val was unique. If you know in advance there will be only one match for the y_val, you could tack on [0] to the end of the indexing, so you get the first result.

这篇关于Python的 - 从创建文件列数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆