1

Say, I have a dictionary of form:

dct = {'A': [1,2,3], 'B': [4,5,6,7]}

How can it be transformed into pandas dataframe such the result will be of the form:

Column1  Column2
A        1
A        2
A        3
B        4
B        5
B        6
B        7
2
  • are those two different columns? Commented Jul 10, 2015 at 10:19
  • yes @AnandSKumar , apparently i don't know how to create a table, sorry for that Commented Jul 10, 2015 at 10:21

2 Answers 2

1

You can use DataFrame.from_dict to import the data:

In [1059]: dct = {'A': [1,2,3], 'B': [4,5,6]}

In [1060]: df = pnd.DataFrame.from_dict(dct)

In [1061]: df
Out[1061]: 
   A  B
0  1  4
1  2  5
2  3  6

And then simply use pandas' very handymelt function to unpivot the dataframe:

In [1062]: pnd.melt(df)
Out[1062]: 
 variable  value
0        A      1
1        A      2
2        A      3
3        B      4
4        B      5
5        B      6
Sign up to request clarification or add additional context in comments.

Comments

0
from itertools import chain
pd.DataFrame(list(chain.from_iterable(
    ((k, v) for v in vals) for (k, vals) in dct.items())),
    columns=('Column1', 'Column2'))

2 Comments

thanks, the code works, it is more general, I forgot that every value in dictionary have different lengths.
I suspected it may be the case and I am glad it works for you.

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.