2017-11-29 1 views
-6

Ich bin ein Neuling in Python, also habe ich Probleme mit vektorisierten Operationen und Indizierung in Python. Ich verstehe vollständig, wie man es im C-Stil mit Element-für-Element-Berechnungen umschreibt, aber es wäre nicht "pythonisch" und lakonisch wie MATLAB-Code. Ich will, dass es kurz und lakonisch ist. Ich brauche den nächsten Code aus MATLAB in Python zu übersetzen:Verwandle MATLAB-Code in Python

for t=2:size(cl, 1) 
    hasData=find(isfinite(retGap(t, :)) & op(t, :) < buyPrice(t, :) & op(t, :) > ma(t, :)); 
    [foo idxSort]=sort(retGap(t, hasData), 'ascend'); 
    positionTable(t, hasData(idxSort(1:min(topN, length(idxSort)))))=1; 
end 

Alle der Arrays sind 1500x497 schwimmt. Ich kann die erste Zeile wie folgt übersetzen:

posCl = cl.iloc[t] 
posOp = op.iloc[t] 
posBp = buyPrice.iloc[t] 
posMa = ma.iloc[t] 
posRg = retGap.iloc[t] 
posRg[pd.notnull(posRg) & (posOp < posBp) & (posOp > posMa)] 

Aber ich habe keine Ahnung, wie die Linien übersetzen mit in lakonischer Weise zu sortieren.

+2

Schritt 1: lernen Python. Schritt 2: Code Python. Alternativ können Sie einen Programmierer einstellen, dies ist kein Code-Konvertierungsdienst. – timgeb

Antwort

4
  • Python Null indizierten
  • MATLAB 1-indexiert

  • MATLAB slice-Notation den Endpunkt

  • Python slice Notation der Endpunkt

  • MATLAB starten schließt umfasst: Schritt: Stopp

  • Python Start : Stop: Schritt

nützliche Links: - http://mathesaurus.sourceforge.net/matlab-numpy.html - http://www.matlabtricks.com/post-23/tutorial-on-matrix-indexing-in-matlab

+0

Danke, aber was du geschrieben hast, ist offensichtlich für mich. Ich habe Probleme mit genau diesem Code. Ich verstehe vollständig, wie man es im C-Stil mit Element-für-Element-Berechnungen umschreibt, aber es wäre nicht "pythonisch" und lakonisch wie MATLAB-Code. Ich will, dass es kurz und lakonisch ist. – Vasiliy

0

Ich habe das Problem gelöst!

for t in range(len(cl)): 
idx = retGap.iloc[t][pd.notnull(retGap.iloc[t]) & \ 
       (op.iloc[t] < buyPrice.iloc[t]) & \ 
       (op.iloc[t] > ma.iloc[t])].sort_values()[:10].index 
positionsTable.iloc[t][idx] = 1 
Verwandte Themen