0
dict_abc = {'A': [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
         'B': [[4, 4, 4], [2, 2, 3],],
         'C': [[4, 6, 0]]
        }

I would like to convert this to a dataframe in the form

   | x | y | z |
A    1   2   3
A    4   5   6
A    7   8   9
B    4   4   4
B    2   2   3
C    4   6   0

3 Answers 3

1

One option, read as Series, explode and convert again to DataFrame:

s = pd.Series(dict_abc).explode()
df = pd.DataFrame(s.to_list(), index=s.index, columns=['x', 'y', 'z'])

output:

   x  y  y
A  1  2  3
A  4  5  6
A  7  8  9
B  4  4  4
B  2  2  3
C  4  6  0
Sign up to request clarification or add additional context in comments.

Comments

0

Use:

In [2471]: x = pd.DataFrame.from_dict(dict_abc, orient='index').stack()
In [2478]: df = pd.DataFrame(x.tolist(), index=x.index, columns=['x', 'y', 'z']).droplevel(1)

In [2479]: df
Out[2479]: 
   x  y  z
A  1  2  3
A  4  5  6
A  7  8  9
B  4  4  4
B  2  2  3
C  4  6  0

5 Comments

Thanks, the only problem im having is these solutions dont work with old pandas, I am stuck with pandas 1.1.5 and can only use this version for now, due to work limitations
This should work with older pandas version as well.
droplevel gives an error
As per this documentation, droplevel is available since pandas version 0.24.0 . What is the error you are facing?
Thanks, it worked after restarting my kernel
0

Using itertools.chain:

from itertools import chain

df = pd.DataFrame(itertools.chain.from_iterable(dict_abc.values()),
                  columns=['x', 'y', 'z'],
                  index=chain.from_iterable([k]*len(v) for k,v in dict_abc.items()))

output:

   x  y  z
A  1  2  3
A  4  5  6
A  7  8  9
B  4  4  4
B  2  2  3
C  4  6  0

Comments

Your Answer

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