我有一个像下面这样的DataFrame,其标识符作为现有dateindex顶部的一列。
pd.DataFrame(index = [pd.to_datetime('2021-01-01'), pd.to_datetime('2021-01-01'),pd.to_datetime('2021-01-02'),pd.to_datetime('2021-01-02'), pd.to_datetime('2021-01-03'),pd.to_datetime('2021-01-03')], columns=['id','A', 'B'], data=[['foo',1,5],['bar',8,12],['foo',7,1], ['bar',5,1], ['foo',4,3],['bar',7,1]])
Out[6]:
id A B
2021-01-01 foo 1 5
2021-01-01 bar 8 12
2021-01-02 foo 7 1
2021-01-02 bar 5 1
2021-01-03 foo 4 3
2021-01-03 bar 7 1
我的目标是为除id之外的每个列(A和B)创建一个新的子数据帧,其中dateIndex作为单个Index,而id(foo,bar)作为列名。预期的输出如下所示:
A
Out[9]:
foo bar
2021-01-01 1 8
2021-01-02 7 5
2021-01-03 4 7
B
Out[11]:
foo bar
2021-01-01 5 12
2021-01-02 1 1
2021-01-03 3 1
A, B = map(df.set_index('id', append=True).unstack().get, ['A', 'B'])
print(A)
id bar foo
2021-01-01 8 1
2021-01-02 5 7
2021-01-03 7 4
print(B)
id bar foo
2021-01-01 12 5
2021-01-02 1 1
2021-01-03 1 3
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句