Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a pandas dataframe out of multiple numpy arrays

I have 2 arrays as below that I want to be converted to dataframe columns:

arr1 = np.array([2, 4, 6, 8])
arr2 = np.array([3, 6, 9, 12])
df_from_arr = pd.DataFrame(data=[arr1, arr2])
print(df_from_arr)

Actual Output:

   0  1  2   3
0  2  4  6   8
1  3  6  9  12

Expected output:

   0  1 
0  2  4 
1  4  6
2  6  9
3  8  12 

How can I get the expected output?

like image 305
Atihska Avatar asked Mar 13 '18 18:03

Atihska


2 Answers

Add T at the end

df_from_arr.T
Out[418]: 
   0   1
0  2   3
1  4   6
2  6   9
3  8  12

Or modify your input arrays

pd.DataFrame(np.hstack((arr1[:,None], arr2[:,None])))
Out[426]: 
   0   1
0  2   3
1  4   6
2  6   9
3  8  12
like image 64
BENY Avatar answered Sep 22 '22 06:09

BENY


You can transpose the DataFrame.

arr1 = np.array([2, 4, 6, 8])
arr2 = np.array([3, 6, 9, 12])
df_from_arr = pd.DataFrame(data=[arr1, arr2]).T
print(df_from_arr)

   0   1
0  2   3
1  4   6
2  6   9
3  8  12
like image 24
Tim Givois Avatar answered Sep 21 '22 06:09

Tim Givois