简体   繁体   中英

Creating a dataframe from a dictionary of different lengths

With the following dictionary:

{'A': [DatetimeIndex([], dtype='datetime64[ns]', name=u'Timestamp', freq=None)],
 'B': [DatetimeIndex(['2010-04-15 16:19:00', '2010-04-15 16:20:00',
                 '2010-04-15 16:23:00'],
            dtype='datetime64[ns]', name=u'Timestamp', length=6, freq=None)]}

I want to create the following dataframe:

                     A                                 B
                    NaN                          2010-04-15 16:19:00
                    NaN                          2010-04-15 16:20:00
                    NaN                          2010-04-15 16:23:00

A and B have different DatetimeIndex lengths so I want to fill the shorter one (in this case column A) with NaN's.

Thanks for your help :)

If you turn your indices into Series objects, the standard DataFrame constructor can do exactly what you want:

>>> data = {'A': [pd.DatetimeIndex([])],
...         'B': [pd.DatetimeIndex(['2010-04-15 16:19:00',
                                    '2010-04-15 16:20:00',
                                    '2010-04-15 16:23:00'])]}
>>> pd.DataFrame({key: pd.Series(val[0], index=val[0])
                  for key, val in data.items()})

                      A                   B
2010-04-15 16:19:00 NaT 2010-04-15 16:19:00
2010-04-15 16:20:00 NaT 2010-04-15 16:20:00
2010-04-15 16:23:00 NaT 2010-04-15 16:23:00

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