1 回答
TA贡献1831条经验 获得超4个赞
使用DataFrame.explodepandas 0.25+ 并使用DataFrame构造函数创建新列:
print (date_df)
a date
0 4 [[2017-02-01 00:00:00, 2017-03-01 00:00:00]]
1 7 [[2017-02-01 00:00:00, 2017-04-01 00:00:00], [...
df = date_df.explode('date')
print (df)
a date
0 4 [2017-02-01 00:00:00, 2017-03-01 00:00:00]
1 7 [2017-02-01 00:00:00, 2017-04-01 00:00:00]
1 7 [2017-02-01 00:00:00, 2017-04-01 00:00:00]
df[['date_start','date_end']] = pd.DataFrame(df.pop('date').values.tolist(), index=df.index)
print (df)
a date_start date_end
0 4 2017-02-01 2017-03-01
1 7 2017-02-01 2017-04-01
1 7 2017-02-01 2017-04-01
编辑:
旧版 pandas 的解决方案:
s = date_df.pop('date')
df = date_df.loc[date_df.index.repeat(s.str.len())]
df[['date_start','date_end']] = pd.DataFrame(np.concatenate(s), index=df.index)
df = df.reset_index(drop=True)
print (df)
a date_start date_end
0 4 2017-02-01 2017-03-01
1 7 2017-02-01 2017-04-01
2 7 2017-02-01 2017-04-01
添加回答
举报