通过使用第二个索引作为列将 pandas 多索引系列转换为数据框 [英] Converting a pandas multi-index series to a dataframe by using second index as columns

查看:97
本文介绍了通过使用第二个索引作为列将 pandas 多索引系列转换为数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有2级多索引和一个列的DataFrame/Series.我想获取二级索引并将其用作列.例如(从 multi -index docs ):

Hi I have a DataFrame/Series with 2-level multi-index and one column. I would like to take the second-level index and use it as a column. For example (code taken from multi-index docs):

import pandas as pd
import numpy as np

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
          ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
s = pd.DataFrame(np.random.randn(8), index=index, columns=["col"])

外观如下:

first  second
bar    one      -0.982656
       two      -0.078237
baz    one      -0.345640
       two      -0.160661
foo    one      -0.605568
       two      -0.140384
qux    one       1.434702
       two      -1.065408
dtype: float64

我想要的是一个索引为[bar, baz, foo, qux]且列为[one, two]的DataFrame.

What I would like is to have a DataFrame with index [bar, baz, foo, qux] and columns [one, two].

推荐答案

您只需要unstack您的系列:

>>> s.unstack(level=1)
second       one       two
first                     
bar    -0.713374  0.556993
baz     0.523611  0.328348
foo     0.338351 -0.571854
qux     0.036694 -0.161852

这篇关于通过使用第二个索引作为列将 pandas 多索引系列转换为数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆