Home > Software design >  how to create a 2,3 panda array/dataframe
how to create a 2,3 panda array/dataframe

Time:05-18

import numpy as np

import pandas as pd

narray = np.array([[1,2,3],[3,4,5]])

row_index = [0]

col_index = ['C0','C1']

pd.DataFrame (data = narray, index = col_index, columns = col_index)

ValueError: Shape of passed values is (2, 3), indices imply (2, 2) #Create a dataframe that contains 2 columns and 3 rows using a numpy array, #using numbers of your choice to fill the array: i have changed the columns , the arrays and even the index however i still get this error

CodePudding user response:

You only need to correct row_index and col_index such that:

import numpy as np

import pandas as pd

narray = np.array([[1,2,3],[3,4,5]])

row_index = [0,1]  #<--- here

col_index = ['C0','C1','C2']  #<--- here

pd.DataFrame (data = narray, index = row_index, columns = col_index)

#output


   C0   C1  C2
0   1   2   3
1   3   4   5

Your row_index should equal number of rows in narray and similarly with col_index.

CodePudding user response:

import pandas as pd
import numpy as np

narray = np.array([[1,2,3],[3,4,5]])

row_index = ['C0','C1']

col_index = ['a', 'b', 'c']

df = pd.DataFrame (data = narray, index = row_index, columns = col_index)
print(df)

Output

    a  b  c
C0  1  2  3
C1  3  4  5

Each nested list you have is a rows. You have two of these, so there are two indexes. The columns are that vertically you should have three of them, and you transmitted two. Also, you passed one element for the rows, but you need two. You can read about indexing here. You can skip indexes and column names, then they will be created automatically. Try to create a dataframe and print it.

df = pd.DataFrame (data = narray)

Output

   0  1  2
0  1  2  3
1  3  4  5
  • Related