将列表列表合并到数据帧pandas中

时间:2018-06-08 07:10:41

标签: python pandas numpy datetime merge

我正在尝试将包含Date索引的列表列表作为每个列表合并到轴= 1的单个数据帧中。 请找到以下代码:

d=[]
for i in range(0,Alpha.shape[0]-1):
    d.append(pd.date_range(start=Alpha.iloc[i]['Month_year'], end=Alpha.iloc[i+1]['Month_year']-pd.DateOffset(days=1), freq='D'))

上面的代码创建了一系列日期索引,如下所示:

[DatetimeIndex(['2014-04-01', '2014-04-02', '2014-04-03', '2014-04-04',
            '2014-04-05', '2014-04-06', '2014-04-07', '2014-04-08',
            '2014-04-09', '2014-04-10', '2014-04-11', '2014-04-12',
            '2014-04-13', '2014-04-14', '2014-04-15', '2014-04-16',
            '2014-04-17', '2014-04-18', '2014-04-19', '2014-04-20',
            '2014-04-21', '2014-04-22', '2014-04-23', '2014-04-24',
            '2014-04-25', '2014-04-26', '2014-04-27', '2014-04-28',
            '2014-04-29', '2014-04-30'],
           dtype='datetime64[ns]', freq='D'),
DatetimeIndex(['2014-05-01', '2014-05-02', '2014-05-03', '2014-05-04',
            '2014-05-05', '2014-05-06', '2014-05-07', '2014-05-08',
            '2014-05-09', '2014-05-10', '2014-05-11', '2014-05-12',
            '2014-05-13', '2014-05-14', '2014-05-15', '2014-05-16',
            '2014-05-17', '2014-05-18', '2014-05-19', '2014-05-20',
            '2014-05-21', '2014-05-22', '2014-05-23', '2014-05-24',
            '2014-05-25', '2014-05-26', '2014-05-27', '2014-05-28',
            '2014-05-29', '2014-05-30', '2014-05-31'],....

我想要的是将列表'd'合并到数据帧中。当我尝试下面的时候,

df=pd.DataFrame()
for i in range(0,len(d)):
    for j in range(0,len(d[i])):
        df.append(d[i][j])

我收到以下错误,

TypeError: cannot concatenate object of type "<class 'pandas._libs.tslib.Timestamp'>"; only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are valid

你能帮我解决一下这个问题吗? 我想以列方式表达所有日期。

提前谢谢

1 个答案:

答案 0 :(得分:2)

我认为需要numpy.concatenate

df = pd.DataFrame(index=np.concatenate(d))