Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

vertical stack numpy array in for loop

I have a list(region_props_list), size = 37, which has the values of 2D numpy arrays like below.
(So, region_props_list[0] is a numpy array.)

I want to vertically stack all the data and make it as a new pandas DataFrame, which has a shape of ($$, 7)

How can I vertically stack the data with a for loop? can someone give me an advice?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

dd

>Solution :

You don’t need a for loop. You can use np.vstack instead:

import numpy as np

lst = [np.array([[1, 2], [3, 4]]), np.array([[5, 6]]), np.array([[7, 8], [9, 10]])]
a = np.vstack(lst)
print(a)

# [[ 1  2]
#  [ 3  4]
#  [ 5  6]
#  [ 7  8]
#  [ 9 10]]

If your goal is to construct a dataframe, then you can use itertools.chain with pd.DataFrame.from_records (without even making the v-stacked array, so that I believe it is memory efficient):

import numpy as np
import pandas as pd
import itertools

lst = [np.array([[1, 2], [3, 4]]), np.array([[5, 6]]), np.array([[7, 8], [9, 10]])]
df = pd.DataFrame.from_records(itertools.chain.from_iterable(lst))
print(df)

#    0   1
# 0  1   2
# 1  3   4
# 2  5   6
# 3  7   8
# 4  9  10

P.S. Please don’t post a screenshot. Make a copy & paste-able minimal example which people can easily work on.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading