0

The dictionary's key is the date, values are a list with different lengths

For example, the dictionary is

dict = { '2017-09-01' : [A B] , '2017-09-02' : [C D E] }

What I want is a Dataframe like

date            Message
2017-09-01      A
2017-09-01      B
2017-09-02      C
2017-09-02      D
2017-09-02      E
niukasu
  • 237
  • 1
  • 4
  • 7

1 Answers1

2

You can use a list comprehension to flatten the dictionary, then construct the data frame from it:

d = { '2017-09-01' : ['A', 'B'] , '2017-09-02' : ['C', 'D', 'E'] }

pd.DataFrame(
    [(k, val) for k, vals in d.items() for val in vals], 
    columns=['date', 'message']
)

#         date  message
#0  2017-09-01        A
#1  2017-09-01        B
#2  2017-09-02        C
#3  2017-09-02        D
#4  2017-09-02        E

Or a longer solution with pandas.stack:

(pd.DataFrame.from_dict(d, 'index').stack()
   .rename('message')
   .rename_axis(('date', ''))
   .reset_index(level=0)
   .reset_index(drop=True))

#         date  message
#0  2017-09-01        A
#1  2017-09-01        B
#2  2017-09-02        C
#3  2017-09-02        D
#4  2017-09-02        E
Psidom
  • 195,464
  • 25
  • 298
  • 322