1

I have a numpy array and I want to convert it into a dataframe.

import numpy as np
import pandas as pd    
nparray = np.array([[1,2,3,4,5],[6,7,8,9,10]])

How do I convert it into a dataframe where the data will be like this:

col1 col2
1      6
2      7
3      8
4      9
5      10
Yuca
  • 6,010
  • 3
  • 22
  • 42
Aditya
  • 113
  • 1
  • 7
  • No I checked that answer before. But I wasn't able to understand how to transpose the array. I have got a lot to learn :) – Aditya Dec 15 '20 at 18:24

4 Answers4

4

My favorite way to transform numpy arrays to pandas DataFrames is to pass the columns in a dictionary:

df = pd.DataFrame({'col1':nparray[0], 'col2':nparray[1]})

However, if you have many columns, you can try:

# Create list of column names with the format "colN" (from 1 to N)
col_names = ['col' + str(i) for i in np.arange(nparray.shape[0]) + 1]
# Declare pandas.DataFrame object
df = pd.DataFrame(data=nparray.T, columns=col_names)

In the second solution, you have to restructure your array before passing it to data = .... That is, you have to rearrange nparray so that is has rows and columns. Numpy has a method for that: you simply add .T to your array: nparray.T.

Arturo Sbr
  • 5,567
  • 4
  • 38
  • 76
4

Use the below code to convert the numpy array into DF.

df = pd.DataFrame(nparray.T, columns=['col1', 'col2'])
1
pd.DataFrame(nparray.T, columns=['col1', 'col2'])

That's it

Amit Amola
  • 2,301
  • 2
  • 22
  • 37
1

You can transpose your np array

Creating the array

>>> import numpy as np
>>> import pandas as pd
>>> nparray = np.array([[1,2,3,4,5],[6,7,8,9,10]])

>>> nparray
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10]])

Creating the pandas DataFrame and transposing

>>> df = pd.DataFrame(data=nparray, index=["col1", "col2"]).transpose()

>>> df
   col1  col2
0     1     6
1     2     7
2     3     8
3     4     9
4     5    10

In time - Without transposing you would get this:

>>> df = pd.DataFrame(data=nparray, index=["col1", "col2"])

>>> df
      0  1  2  3   4
col1  1  2  3  4   5
col2  6  7  8  9  10
Paulo Marques
  • 775
  • 4
  • 15