简体   繁体   English

Pandas:将带有 DatetimeIndex 的列表字典转换为 DataFrame

[英]Pandas: Convert Dict of Lists with DatetimeIndex to DataFrame

I need some help from pandas experts :) I need to efficiently create DataFrame from dictionary that contains list of two DatetimeIndexes as values.我需要熊猫专家的一些帮助:) 我需要从包含两个 DatetimeIndexes 列表作为值的字典有效地创建 DataFrame。

Here is short example of such dictionary:这是此类字典的简短示例:

import pandas as pd

d = {
  871:[pd.date_range('20180131', '20180331', freq='M', normalize=True),
       pd.date_range('20180228', '20180430', freq='M', normalize=True)],
  872:[pd.date_range('20180228', '20180331', freq='M', normalize=True),
       pd.date_range('20180331', '20180430', freq='M', normalize=True)]}

d
Out[3]: 
{871: [DatetimeIndex(['2018-01-31', '2018-02-28', '2018-03-31'], dtype='datetime64[ns]', freq='M'),
  DatetimeIndex(['2018-02-28', '2018-03-31', '2018-04-30'], dtype='datetime64[ns]', freq='M')],
 872: [DatetimeIndex(['2018-02-28', '2018-03-31'], dtype='datetime64[ns]', freq='M'),
  DatetimeIndex(['2018-03-31', '2018-04-30'], dtype='datetime64[ns]', freq='M')]}

What I want to get is a DataFrame where dict keys used as indexes and two pd.Timestamp columns that correspond to those two DatetimeIndexes from above.我想要的是一个 DataFrame,其中 dict 键用作索引和两个 pd.Timestamp 列,它们对应于上面的两个 DatetimeIndexes。

Here is how it should look like:它应该是这样的:

result_df
Out[6]: 
         Start        End
871 2018-01-31 2018-02-28
871 2018-02-28 2018-03-31
871 2018-03-31 2018-04-30
872 2018-02-28 2018-03-31
872 2018-03-31 2018-04-30

PS Actual task is to split large DataFrame with date ranges, such as below, to single months. PS实际任务是将具有日期范围的大型 DataFrame(如下所示)拆分为单个月份。

df_original
Out[19]: 
           Start        End
Index                      
871   2018-01-31 2018-02-28
872   2018-02-28 2018-04-30

Large is several hundred thousand rows.大是几十万行。

Use:用:

d1 = {k: pd.DataFrame(list(zip(*v)), columns=['Start','End']) for k, v in d.items()}
df = pd.concat(d1).reset_index(level=1, drop=True)
print (df)
         Start        End
871 2018-01-31 2018-02-28
871 2018-02-28 2018-03-31
871 2018-03-31 2018-04-30
872 2018-02-28 2018-03-31
872 2018-03-31 2018-04-30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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