Escachator
Escachator

Reputation: 1881

Creating dataframes in Python: issue with columns and index

I am trying to create a DataFrame with multiple indices and one column. If I type the following:

InitialPosition=pd.DataFrame( [1000000,1,1] ,index=['Cash'],columns=['a','b','c'] )

I get an error:

ValueError: Shape of passed values is (1, 3), indices imply (3, 1) 

If I change the array to columns, like:

InitialPosition=pd.DataFrame( [[1000000],[1],[1]] ,index=['Cash'],columns=['a','b','c'] )

then the error I have is:

AssertionError: 3 columns passed, passed data had 1 columns 

Do you know why this is happening?

One solution is to do:

InitialPosition=pd.DataFrame( [1000000,1,1] ,columns=['Cash'],index=['a','b','c'] ).T

but doesn't look very elegant.

Upvotes: 0

Views: 1715

Answers (1)

Anzel
Anzel

Reputation: 20553

The problem is, you're assigning index as 'Cash' which is only 1 index. and [1000000,1,1] is passing 3 rows of data.

And look at this:

InitialPosition=pd.DataFrame( [1000000,1,1] ,columns=['Cash'],index=['a','b','c'] ).T

You're passing 3 rows of data, 1 x columns and 3 indexes, which matches the structure of a dataframe.

However think of the arrays in a DataFrame like x,y coordinates as in columns, rows structure, here should be what your DataFrame looks like:

InitialPosition=pd.DataFrame( [[1000000, 1, 1]] ,columns=['a', 'b', 'c'],index=['cash'] )

[[10000000, 1, 1]] translates to like on rows[0], columns[0], columns[1], columns[2] = ..., with columns label 'a','b','c' and 1 x index 'cash'.

Alternatively,

InitialPosition=pd.DataFrame( [[1000000],[1],[1]] ,columns=['Cash'],index=['a','b','c'] ).T

which, [[1000000], [1], [1]] translates to rows[0], columns[0] = [1000000], rows[1], columns[0] = 1, rows[2], columns[0] = 1, with 1 x column 'Cash', and 3 x indexes 'a','b','c' accordingly, then transpose it at the end.

Both will give you this result:

InitialPosition

            a  b  c
cash  1000000  1  1

And I strong advise you read this 10 Minutes to pandas which explains things rather thoroughly yet not too hard to digest.

Upvotes: 1

Related Questions