1

I have a function that is giving multiple arrays and I need to but these into a matrix.

def equations(specie, elements):
 for x in specie:
   formula = parse_formula(x)
   print extracting_columns(formula, elements)

what im getting:

equations(['OH', 'CO2','C3O3','H2O3','CO','C3H1'], ['H', 'C', 'O']) 
[ 1.  0.  1.]
[ 0.  1.  2.]
[ 0.  3.  3.]
[ 2.  0.  3.]
[ 0.  1.  1.]
[ 1.  3.  0.]

i need it to give me ([[1,0,1][[ 0., 1., 2.][ 0. , 3. , 3.][ 2. , 0. ,3.][ 0. , 1. ,1.][ 1. , 3., 0.]])

I have been messing with this for a while and cant figure it out.

If you need my past functions they are below:

def extracting_columns(specie, elements):
  species_vector=zeros(len(elements))
  for (el,mul) in specie:
    species_vector[elements.index(el)]=mul

  return species_vector

1 Answer 1

2

Instead of printing out each row, collect them into a list (e.g. result):

def equations(specie, elements):
    result = []
    for x in specie:
        formula = parse_formula(x)
        result.append(extracting_columns(formula, elements))
    return np.array(result)

For example,

import numpy as np
import re

def equations(specie, elements):
    result = []
    for x in specie:
        formula = parse_formula(x)
        result.append(extracting_columns(formula, elements))
    return np.array(result)

def extracting_columns(formula, elements):
    return [formula.get(e, 0) for e in elements]

def parse_formula(formula):
    elts = iter(re.split(r'([A-Z][a-z]*)',formula)[1:])
    return {element:toint(num) for element, num in zip(*[elts]*2)}

def toint(num):
    try:
        return int(num)
    except ValueError:
        return 1

print(equations(['OH', 'CO2','C3O3','H2O3','CO','C3H1'], ['H', 'C', 'O']))

yields

[[1 0 1]
 [0 1 2]
 [0 3 3]
 [2 0 3]
 [0 1 1]
 [1 3 0]]
Sign up to request clarification or add additional context in comments.

1 Comment

@user1819717: Yes. If the array is called arr, then you are looking for arr.T.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.