2016-03-25 12 views
0

numpyの配列に高い値のインデックスを見つける:今すぐストアと私は、このscructure含まれているファイルのロードに<code>numpy.loadtxt</code>を使用

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 

は、私が(最初の行を除く)最初の列はのインデックスを格納することを必要としますそのラインの中でより高い価値があります。

最後に、この配列をオリジナルと同じ番号書式のファイルに保存します。

ありがとうございます。

答えて

3

は、あなたがこのようなnumpy.argmaxなものを使用できます:ネイティブにこのレイアウトを管理するpandas、でそれを行うことがより便利である

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)か否かを判定する。

1

データは、列とインデックスを持つDataframeのように見えます。データ型は同質ではありません。

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 
関連する問題

 関連する問題