1 回答
TA贡献1943条经验 获得超7个赞
以下对我有用:
data = {'date': ['2014-05-01','2014-05-01','2014-05-01','2014-05-01',
'2014-05-02','2014-05-02','2014-05-02','2014-05-03',
'2014-05-03','2014-05-03'],'id':[1, 2, 3, 4, 1,
2, 3, 1, 2, 4],'obs': [10, 5, 7, 3, 2,4, 3, 8, 6, 11]}
df = pd.DataFrame(data, columns = ['date', 'id','obs'])
result = df.set_index(['id','date']).unstack(fill_value='.').stack().sort_index(level=1).reset_index()
result = result.set_index('date')
In [1]: result
Out[1]:
id obs
date
2014-05-01 1 10
2014-05-01 2 5
2014-05-01 3 7
2014-05-01 4 3
2014-05-02 1 2
2014-05-02 2 4
2014-05-02 3 3
2014-05-02 4 .
2014-05-03 1 8
2014-05-03 2 6
2014-05-03 3 .
2014-05-03 4 11
添加回答
举报