简体   繁体   中英

Python: Append array columns in a for loop

I have the following problem.

I have several parameters, all integers or floats, and I want to stack them in a for loop. I tried different thinks like:

for i in range(0,19000):
    parameterCombinationsResults = np.array([]).reshape(0,12)
    parameterCombinationsResults = np.r_[parameterCombinationsResults,[[self.cR,self.fD,s[0]+1,s[1]+1,self.cI,self.cO,self.fI,self.fO,maxJC,maxSensitivity,maxSpecifity,numberOfCells]]]

The problem is, that in every loop iteration the old values are stacked as well of course, so I have in every loop the old results+the new results which will result in an array with thousands of copies of the old results. Is there a way like list append. I know arrays are immutable but maybe there is a workaround?

In the end I want to save all this parametercombination results in a csv. It dont have to be arrays I would also be itnerested in a list approach, the important thing is to save them in a csv and that it has to be very fast.

There's a numpy method called vstack. Here's an example from the numpy website

a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
np.vstack((a,b))
array([[1, 2, 3],[2, 3, 4]])

https://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html

Applying this to your code would make it look like

pcr_stack = parameterCombinationsResults  #need to start one for vstack to work

for i in range(0,19000):
    pcr_stack = vstack([pcr_stack,[self.cR,self.fD,s[0]+1,s[1]+1,self.cI,self.cO,self.fI,self.fO,maxJC,maxSensitivity,maxSpecifity,numberOfCells]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM