1
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

  • By writing `col_index = ['C0','C1']; pd.DataFrame( ... index = col_index, columns = col_index)`, you're explicitly instructing your DataFrame to have 2 rows and 2 columns. You cannot expect to fit a 2x3 array to a 2x2 DataFrame. – jfaccioni May 17 '22 at 20:33

2 Answers2

0
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
inquirer
  • 4,286
  • 2
  • 9
  • 16
0

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.

Hamzah
  • 8,175
  • 3
  • 19
  • 43