Kben59
Kben59

Reputation: 388

Creating a numpy array after a for loop

I have this DataFrame:

df4=pd.DataFrame({'Date':['2020-05-19'],
                 'A':[153],
                 'B':[139],
                 'C':[165],
                 'D':[165],
                 'E':[123],
                 'F':[135],
                 'G':[137],})

df4['Date']=pd.to_datetime(df4['Date'])
df4 = df4.set_index('Date')

Then I transformed df in order to work with numpy

row=df4.to_records()[0]

amount = 10000

And I created this for loop:

for i in np.arange(1,len(row),1):
    test=amount/row[i] if row[i]<=150 else 0
    print(test)

This is the result of the variable test:

0
71.94244604316546
0
0
81.30081300813008
74.07407407407408
72.99270072992701

And I would like to know if there is a way to transform all the results of test into a numpy array? Hence the result should be something like this :

test = [0,71.94244604316546,0,0,81.30081300813008,74.07407407407408,72.99270072992701]

Thanks

Upvotes: 0

Views: 31

Answers (2)

GPhilo
GPhilo

Reputation: 19123

Alternatively to the list option, you can get the array directly from the iterator:

res = np.fromiterator((amount/row[i] if row[i]<=150 else 0 for i in np.arange(1,len(row),1)), dtype=int count=len(row)-1)

Note that, since you know how long the iterable is, you can pass the count parameter to make it slightly faster (numpy knows how much memory to preallocate and skips resizing as it loops)

Upvotes: 1

Narendra Prasath
Narendra Prasath

Reputation: 1531

You can create list and convert to numpy array:

import numpy as np
output = []
for i in np.arange(1,len(row),1):
    test=amount/row[i] if row[i]<=150 else 0
    output.append(test)
np.array(output)

Upvotes: 1

Related Questions