Home > OS >  vertical stack numpy array in for loop
vertical stack numpy array in for loop

Time:11-17

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?

dd

CodePudding user response:

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):

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.

  • Related