python - 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
解决方案
我认为需要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
推荐阅读
- jenkins - Jenkins/Groovy- Job DSL 插件 - git() vs git{}
- reactjs - 通过状态对象获取道具
- python - Docker 上的 Django 正在启动,但浏览器给出空响应
- r - 在 R 中创建更准确的线性回归模型
- pandas - 当我尝试将日期从 Pandas 传递到条形图竞赛模块时出现错误
- mysql - 从一个表中获取行数,其中另一个表中的至少一个相关项与条件匹配
- javascript - 了解 setTimeout 及其在 JavaScript Promises 中的实现
- office-js - Word Web 加载项仅在清理缓存后才有效
- javascript - 如何在映射反应中使用 createdAt 对数组进行排序?
- r - 提取以下单个单词的字符: