在numpy数组中存储和查找更高的值索引

2024-09-27 21:31:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用numpy.loadtxt加载了一个包含以下scructure的文件:

99  0           1           2           3           ...     n
46  0.137673    0.147241    0.130374    0.155461    ...     0.192291
32  0.242157    0.186015    0.153261    0.152680    ...     0.154239
77  0.163889    0.176748    0.184754    0.126667    ...     0.191237
12  0.139989    0.417530    0.148208    0.188872    ...     0.141071 
64  0.172326    0.172623    0.196263    0.152864    ...     0.168985
50  0.145201    0.156627    0.214384    0.123387    ...     0.187624
92  0.127143    0.133587    0.133994    0.198704    ...     0.161480

现在,我需要第一列(除了第一行)存储该行中较高值的索引。你知道吗

最后,将此数组保存在与原始数组相同的数字格式的文件中。你知道吗

谢谢


Tags: 文件numpy格式数字数组loadtxt高值scructure
2条回答

你能用这样的numpy.argmax吗:

import numpy as np

# This is a simple example. In your case, A is loaded with np.loadtxt
A = np.array([[1, 2.0, 3.0], [3, 1.0, 2.0], [2.0, 4.0, 3.0]])
B = A.copy()

# Copy the max indices of rows of A into first column of B
B[:,0] = np.argmax(A[:,1:], 1)

# Save the results using np.savetxt with fmt, dynamically generating the
# format string based on the number of columns in B (setting the first
# column to integer and the rest to float)
np.savetxt('/path/to/output.txt', B, fmt='%d' + ' %f' * (B.shape[1]-1))

注意,np.savetxt允许格式化。你知道吗

此示例代码没有说明您希望跳过第一行的事实,您可能希望从np.argmax的结果中减去1,这取决于剩余列中的索引是否包含索引列(0)。你知道吗

您的数据看起来像一个带有列和索引的数据帧:数据类型是非同构的。使用pandas更方便,它本机管理此布局:

import pandas as pd
a=pd.DataFrame.from_csv('data.txt',sep=' *')
u=a.set_index(a.values.argmax(axis=1)).to_string()
with open('out.txt','w') as f : f.write(u)

那么out.txt就是

          0         1         2         3         4
4  0.137673  0.147241  0.130374  0.155461  0.192291
0  0.242157  0.186015  0.153261  0.152680  0.154239
4  0.163889  0.176748  0.184754  0.126667  0.191237
1  0.139989  0.417530  0.148208  0.188872  0.141071
2  0.172326  0.172623  0.196263  0.152864  0.168985
2  0.145201  0.156627  0.214384  0.123387  0.187624
3  0.127143  0.133587  0.133994  0.198704  0.161480

相关问题 更多 >

    热门问题