/  Technology   /  Python program to convert the array into DataFrame
Python program to convert the array into DataFrame

Python program to convert the array into DataFrame

By using the following steps below, we can convert an array into Dataframe

Step 1:

We have to import 2 libraries

  1. Pandas
  2. Numpy

 

Below is the code:

import numpy as np
import pandas as pd

 

Step 2: Let us pass the list of values to an array

 

dataset = np.array([
                  [1,2,3,4,5],
                  ['Sofa set', 'table','night lamp','side bed','recliner'],
                  [50000, 3000, 1500, 20000 , 35000],
                  ['Jay','Akhil','Ravi','Divya','Bindu'],
                  ['wood','plastic','iron','wood','metal'] ])

 

Step 3: In next step, we take another line and name it as “a”. In this line “a”, we add only the first column of the dataset i.e. [1,2,3,4,5] and we also add reshape function in order to give the shape to our output.

 

a = np.array([1,2,3,4,5]).reshape(-1,1)

 

Step 4: Here we apply the range and length functions to the dataset line i.e our step 1 line. Range function helps to generate a sequence and it also loops the data and length function helps to get the length.

 

for i in range(1,len(dataset)):

 

Step 5: We write another line and give it a name “i” where we are assigning range and reshape functions to our dataset hence adding “dataset” to this line.

 

i = dataset[i].reshape(-1,1)

 

Step 6: Here we will take our previous line “a”(where reshape function was added initially and first column of dataset was added). After that we have to apply np.hstack. hstack is another function in python which will stack the array in horizontal sequence. We add our lines “a” and “i”, as these are the lines which need to be stacked horizontally.

 

a = np.hstack((a,i))

 

Step 7: as we have to convert the array into DataFrame we will use pd.DataFrame and add columns to the values which we have taken for our dataset

 

df = pd.DataFrame(data=a, columns=["Series","Furniture", "cost", "Brand", "product"])
df

 

Step 8: We run all the lines together and we will get our output

 

Python program to convert the array into DataFrame

 

 

 

 

Leave a comment