2

I have two lists and an array that need to be transformed into a DataFrame. This is more or less what I have:

listA = ['a', 'b', 'c', 'd']
listB = ['x', 'y', 'z']

array = [[10, 11, 12], [20, 21, 22], [30, 31, 32], [40, 41, 42]]

I want my DataFrame to be like this:

enter image description here

I've tried creating the DataFrame by inserting the lists into

pd.Dataframe()

and then specifying what the column's name should be. But no luck so far.

2 Answers 2

1

pd.MultiIndex.from_product helps here; it will take the cartesian product of two lists given and give a MultiIndex with 2 levels populated as such:

>>> pd.DataFrame(np.ravel(array),
                 index=pd.MultiIndex.from_product([listA, listB]), 
                 columns=["value"])
     value
a x     10
  y     11
  z     12
b x     20
  y     21
  z     22
c x     30
  y     31
  z     32
d x     40
  y     41
  z     42
  • values are the raveled (flattened) array
  • index is the product of the two lists
  • columns is the "value" which is the only one.
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! But, is there a way to maintain each column as described in the picture? The whole idea is to access the "value" column by looking up a (listA, listB) location.
hi Diego, you can do that with, for example, df.loc[("b", "z"), "value"]: this will look up the value of the "value" column where listA is "b" and listB is "z". Therefore it gives 22. Is that what you meant? Currently, the listA and listB values are in the index as a MultiIndex with 2 levels. That allows us to reach values with .loc as shown above with a tuple in the row-selection part.
0
out = pd.DataFrame(array, index=listA, columns=listB).stack()

out:

a  x    10
   y    11
   z    12
b  x    20
   y    21
   z    22
c  x    30
   y    31
   z    32
d  x    40
   y    41
   z    42
dtype: int64

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.