简体   繁体   中英

Create a dataframe from dictionary - python

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

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 handy melt 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
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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM