首页 > 解决方案 > Building a multi-index db

问题描述

I am a python newbie. I have two lists that I need to build a MultiIndex object for. The lists are Letters = ['A', 'B', 'C'] and numbers = list(range(10)). I need to index a Series of random numbers (called S). I have compiled some code but keep getting errors. Any assistance would be appreciated.

import pandas as pd
letters = ['A', 'B', 'C']
numbers = list(range(10))

def s(num, lower=0, upper=9):
    return [random.randrange(lower,upper+1) for i in range(30)]

df_test = pd.DataFrame.from_records(letters, columns=['letters'], numbers, 
df

As you can imagine, this is not working. If anyone can provide some suggestions I would be truly appreciative.

Thanks

标签: pythonpandasmulti-index

解决方案


我认为需要Series创建MultiIndex.from_product

s = pd.Series(s(10),index=pd.MultiIndex.from_product([letters, numbers], names=['let','num']))
print (s)
let  num
A    0      4
     1      2
     2      3
     3      8
     4      4
     5      2
     6      9
     7      9
     8      0
     9      4
B    0      0
     1      8
     2      2
     3      0
     4      0
     5      8
     6      1
     7      7
     8      7
     9      6
C    0      4
     1      2
     2      5
     3      8
     4      1
     5      4
     6      5
     7      2
     8      0
     9      2
dtype: int64

推荐阅读