Python 如何在dataframe中为两行创建一个索引?
我想在我的数据框架中将我的年数作为索引。但每年指的是两行。我该怎么做 这就是我所拥有的:Python 如何在dataframe中为两行创建一个索引?,python,pandas,Python,Pandas,我想在我的数据框架中将我的年数作为索引。但每年指的是两行。我该怎么做 这就是我所拥有的: TYPE Jan Feb 2019 - A 1 2 2019 - B 4 4.3 这就是我想要的: TYPE Jan Feb 2019 - A 1 2 B 4 4.3 看起来您希望您的数据框架具有多个索引,年份和类型列。这里有一些关于 我认为这个链接中的代码示例与您期望的输出非常相关 In [1]: array
TYPE Jan Feb
2019 - A 1 2
2019 - B 4 4.3
这就是我想要的:
TYPE Jan Feb
2019 - A 1 2
B 4 4.3
看起来您希望您的数据框架具有多个索引,年份和
类型
列。这里有一些关于
我认为这个链接中的代码示例与您期望的输出非常相关
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
使用索引和列创建多索引:
df = pd.DataFrame({'year': [2019, 2019 ],'Type': ['A',' B'],'Jan': [1, 4,],'Feb': [2, 4.3]})
df = df.set_index(['year', 'Type'])
print(df)
请参阅此资源以获得更详细的解释
df.groupby('year')。head()应该是groupby year列,
head()
将允许您查看它。@amanb year已经是一个索引。如果您想要简单的单级索引,那么您不应该做您想做的事情,因为我相信它需要您将第二个值更改为'
。但是如果你想要一个x年类型的多重指数,那么你会得到上面的(只需要指数中的类型)