1

I would like to create a dataframe with a dictionnary. I created my dictionnary, i would like convert this in Dataframe with one columns for the months and the second for value.

Do you have an idea for to resolve my problem ?

My dictionary : {'Jan': [1, 5], 'Apr': [2, 6], 'Mar': [3, 7], 'June': [4, 8]}

            import pandas as pd
        from collections import defaultdict


        # d = {('20170330', 'A'): {'earn': '16.02'},('20170331', 'A'): {'earn': '25.68'},('20170330', 'AA'): {'earn': '321321'}}

        months = ['Jan','Apr','Mar','June','Jan','Apr','Mar','June']
        days = [1,2,3,4,5,6,7,8]

        zipped = zip(months, days)

        d = {}
        for items in zipped:
            res = d.setdefault(items[0], [])
            res.append(items[1])

        print(d)

Thnks you !

Flo Cp
  • 281
  • 2
  • 13
  • 1
    Does this answer your question? [Convert Python dict into a dataframe](https://stackoverflow.com/questions/18837262/convert-python-dict-into-a-dataframe) – M_S_N Jan 23 '20 at 17:22
  • you need :`pd.DataFrame(d)` – YOLO Jan 23 '20 at 17:28
  • Yes, but i want one columns with the months and just one columns with the value. If a use pd.Dataframe(d) i will have my dataframe Transposed. So, i used df.T but i have one columns for the months and two columns for the value... – Flo Cp Jan 23 '20 at 17:32
  • It's ok ! I find an solution, i use https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html and i don't use the dictionnary ! Thks – Flo Cp Jan 23 '20 at 17:41

1 Answers1

1

You can use stack:

pd.DataFrame(d).stack() \
    .rename_axis([None, 'Month']) \
    .to_frame('Day') \
    .reset_index(level=1) \
    .reset_index(drop=True)

stack produces a Series so the last 4 lines are just trying to produce a DataFrame and get it into shape.

Result:

  Month  Day
0   Jan    1
1   Apr    2
2   Mar    3
3  June    4
4   Jan    5
5   Apr    6
6   Mar    7
7  June    8
Code Different
  • 90,614
  • 16
  • 144
  • 163