My goal is to make a numpy array out of dataframes. There are 2 dataframes, which have 2 rows and 5 columns for each(If they were numpy array, their shapes are (2,5) for each). Is there a way to make numpy array which has shape (2, 2, 5) out of these dataframes?(There are 2 datataframe which has (2,5) shape, so (2,2,5) it is.)
import pandas as pd
import numpy as np
A1 = pd.DataFrame({'O':[2,4],'H':[4,8],'L':[1,2],'V':[100, 120],'C':[3,7]}) # shape (2,5) Table
A2 = pd.DataFrame({'O':[20,40],'H':[40,80],'L':[10,20],'V':[1000, 1200],'C':[30,70]}) # shape (2,5) Table
# Is there a way to make (2, 2, 5) numpy array from dataframe A1, A2?
CodePudding user response:
Just concat then reshape
pd.concat([A1,A2]).values.reshape(2,2,5)
Out[398]:
array([[[ 2, 4, 1, 100, 3],
[ 4, 8, 2, 120, 7]],
[[ 20, 40, 10, 1000, 30],
[ 40, 80, 20, 1200, 70]]])
pd.concat([A1,A2]).values.reshape(2,2,5).shape
Out[399]: (2, 2, 5)
CodePudding user response:
One way is to stack them using np.stack([])
import numpy as np
np.stack([A1.values, A2.values])
np.stack([A1.values, A2.values]).shape
Output : (2, 2, 5)