如何在数据帧中为两行提供一个索引



我想将我的年份作为数据帧中的索引。但每年指两行。我该怎么做?

这是我所拥有的:

       TYPE Jan Feb 
2019 -  A    1   2
2019 -  B    4  4.3

这就是我想要的:


       TYPE Jan Feb 
2019 -  A    1   2
        B    4  4.3

看起来您希望数据帧具有多个索引、年份和Type列。 以下是有关高级索引的一些文档

我认为该链接中的此代码示例与您想要的输出非常相关

In [1]: arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
   ...:           ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
   ...: 
In [2]: tuples = list(zip(*arrays))
In [3]: tuples
Out[3]: 
[('bar', 'one'),
 ('bar', 'two'),
 ('baz', 'one'),
 ('baz', 'two'),
 ('foo', 'one'),
 ('foo', 'two'),
 ('qux', 'one'),
 ('qux', 'two')]
In [4]: index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
In [5]: index
Out[5]: 
MultiIndex([('bar', 'one'),
            ('bar', 'two'),
            ('baz', 'one'),
            ('baz', 'two'),
            ('foo', 'one'),
            ('foo', 'two'),
            ('qux', 'one'),
            ('qux', 'two')],
           names=['first', 'second'])
In [6]: s = pd.Series(np.random.randn(8), index=index)
In [7]: s
Out[7]: 
first  second
bar    one       0.469112
       two      -0.282863
baz    one      -1.509059
       two      -1.135632
foo    one       1.212112
       two      -0.173215
qux    one       0.119209
       two      -1.044236
dtype: float64

使用索引和列创建 MultiIndex:

df = pd.DataFrame({'year': [2019, 2019 ],'Type': ['A',' B'],'Jan': [1, 4,],'Feb': [2, 4.3]})
df = df.set_index(['year', 'Type'])
print(df)

关注此资源以获取更详细的说明https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html

最新更新