2

I have one numpy array of the form:

np.Array1 = 

[
   ['2019-12-01' '0.03555' '0.03' '0.03' '0.03'],
   ['2019-12-02' '0.03' '0.03' '1' '0.03']
]

and a second:

np.Array2 = 

[
   array(['2019-12-01', '1', '1', '1', '1']),
   array(['2019-12-02', '1', '1', '1', '20'])
]

Is there a way for me so do something along the lines of:

Sum each element where npArray1.col1 = npArray2.col1 - i.e : when the dates are the same add element by element (excluding the date)

'2019-12-01' = '2019-12-01' so [0.03555+1, 0.03+1, 0.03+1, 0.03+1]

I get that I am probs going about this the wrong way, by varying the types in the same array

Any advice is appreciated on a better way of add values based on conditional logic.

2 Answers 2

2

You could do this by converting your arrays to pandas dataframes with the date as the index, and using add:

import numpy as np
import pandas as pd

a1 = np.array( [['2019-12-01', '0.03555', '0.03', '0.03', '0.03'],
                ['2019-12-02', '0.03', '0.03', '1', '0.03']] )

a2 = np.array([['2019-12-01', '1', '1', '1', '1'],
               ['2019-12-02', '1', '1', '1', '20']])

# convert to dataframe and set the date as the index
# also convert to floats:
df1 = pd.DataFrame(a1).set_index(0).astype(float)
df2 = pd.DataFrame(a2).set_index(0).astype(float)


df1.add(df2, fill_value = 0)

You can then get it back as a numpy array in your original format by converting back to string, reseting the index, and taking the values:

df1.add(df2, fill_value = 0).astype(str).reset_index().values
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this, I did something similar, I converted the original source of NumPy arrays to return an array of dicts instead, then pd.DataFrame(self.buildArrayOfDicts()).explode('dates') - I then did a df.set_index('dates) making it easier to sum() later down the line
0

This worked for me, and it not requires pandas:

import numpy as np

a1 = [
    np.array(['2019-12-01', '0.03555', '0.03', '0.03', '0.03']),
    np.array(['2019-12-02', '0.03', '0.03', '1', '0.03'])
]

a2 = [
    np.array(['2019-12-01', '1', '1', '1', '1']),
    np.array(['2019-12-02', '1', '1', '1', '20'])
]

def array_adder(A, B):
    C = []
    for outer, outer2 in zip(A, B):
        temp = []
        if len(outer) == len(outer2):
            for inner, inner2 in zip(outer, outer2):
                if len(temp) < 1:
                    temp.append(inner)
                else:
                    temp.append(float(inner) + float(inner2))
            C.append(temp)
        else:
            print('Arrays must have the same length..')
            break
    return C

print(array_adder(a1, a2))

Comments

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.