Home > database >  Looping over vectors in python (analogous to Pandas columns)
Looping over vectors in python (analogous to Pandas columns)

Time:06-06

I have a number of analogous operations that I would like to perform on different vectors. What is the 'pythonesque' way of 'looping' over these variables to save lines?

import numpy as np

length = 10

l = np.ones(length, dtype = int)
r = np.ones(length, dtype = int)
v = np.ones(length, dtype = int)
w = np.ones(length, dtype = int)
q = np.ones(length, dtype = int)

new_l = np.ones(length, dtype = int)
new_r = np.ones(length, dtype = int)
new_v = np.ones(length, dtype = int)
new_w = np.ones(length, dtype = int)
new_q = np.ones(length, dtype = int)

l = 0.05 * new_l   0.95 * l
r = 0.05 * new_r   0.95 * r
v = 0.05 * new_v   0.95 * v
w = 0.05 * new_w   0.95 * w
q = 0.05 * new_q   0.95 * q

If these were columns in a Pandas dataframe, I would write:

import pandas as pd

length = 10

df = pd.DataFrame(index = range(length))

for v in ['l', 'r', 'v', 'w', 'q']:
    
    df[f'{v}'] = 1
    df[f'new_{v}'] = 1
    df[f'{v}'] =  0.05 * df[f'new_{v}']   0.95 * df[f'{v}']
   

What's the most elegant way to do this for vectors?

CodePudding user response:

You can stack them into a single array with np.stack() and then apply the operations on the resulting array:

array = np.stack([l, r, v, w, q])
new_array = np.stack([new_l, new_r, new_v, new_w, new_q])

result = 0.05*new_array   0.95*array
l, r, v, w, q = result
l

Output:

array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
  • Related