Home > database >  4 I am trying to put array into a pandas dataframe
4 I am trying to put array into a pandas dataframe

Time:05-15

import pandas as pd
import numpy as np
zeros=np.zeros((6,6))
arra=np.array([zeros])

rownames=['A','B','C','D','E','F']
colnames=[['one','tow','three','four','five','six']]
df=pd.DataFrame(arra,index=rownames,columns=colnames)
print(df)

Error: ValueError: Must pass 2-d input. shape=(1, 6, 6)

My desired output is :

        A  B C D E F
one     0  0 0 0 0 0
tow     0  0 0 0 0 0
three   0  0 0 0 0 0 
four    0  0 0 0 0 0
five    0  0 0 0 0 0
six     0  0 0 0 0 0

CodePudding user response:

Try this

pd.DataFrame(np.zeros((6,6)), columns=list('ABCDEF'), index=['one','tow','three','four','five','six'])

CodePudding user response:

Try this

zeros=np.zeros((6,6), dtype=int)
df=pd.DataFrame(zeros, columns=['A','B','C','D','E','F'], index=['one','tow','three','four','five','six'])

Understand that in your questions 'A','B','C','D','E','F' these are column names and 'one','tow','three','four','five','six' are indexes, you have confused them with rows and columns.

The reason you got that error is because of the line arra=np.array([zeros]) which converts 2d array to 1d array (like how its given below - see '[[[' which means it is 1d array of 2d array ), but you need 2d array to create a dataframe.

array([[[0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0]]])

Hope this helped!

CodePudding user response:

If you want to initialize your DataFrame with a single value, you don't need to bother creating a 2D array, just pass the desired scalar to the DataFrame constructor and it will broadcast:

import pandas as pd

rownames=['A','B','C','D','E','F']
colnames=[['one','tow','three','four','five','six']

df=pd.DataFrame(0, index=rownames, columns=colnames)

print(df)

Output:

  one tow three four five six
A   0   0     0    0    0   0
B   0   0     0    0    0   0
C   0   0     0    0    0   0
D   0   0     0    0    0   0
E   0   0     0    0    0   0
F   0   0     0    0    0   0
  • Related