13

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?

3 Answers 3

13

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
Sign up to request clarification or add additional context in comments.

Comments

11

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

Comments

7

You can also do this:

arr1 = np.array([2, 4, 6, 8])
arr2 = np.array([3, 6, 9, 12])
df_from_arr = pd.DataFrame({0:arr1,1:arr2})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.