Python Pandas convert GroupBy object to DataFrame
问题
有两个问题看起来很相似,但它们不是同一个问题:这里和这里。它们都调用
构造一个示例
1 2 3 4 5 6 | data_list = [] for name in ["sasha","asa"]: for take in ["one","two"]: row = {"name": name,"take": take,"score": numpy.random.rand(),"ping": numpy.random.randint(10, 100)} data_list.append(row) data = pandas.DataFrame(data_list) |
上面的
1 2 3 4 5 | name ping score take 0 sasha 72 0.923263 one 1 sasha 14 0.724720 two 2 asa 76 0.774320 one 3 asa 71 0.128721 two |
我要做的是按列"name"和"take"分组(按这个顺序),这样我就可以得到一个由列"name"和"take"构造的多索引索引的
1 2 3 4 5 6 | score ping name take sasha one 0.923263 72 two 0.724720 14 asa one 0.774320 76 two 0.128721 71 |
我怎样才能做到?如果我做
您需要
1 2 3 4 5 6 7 8 | data = data.set_index(['name','take']) print (data) ping score name take sasha one 46 0.509177 two 77 0.828984 asa one 51 0.637451 two 51 0.658616 |