python - pandas:construct dataframe with > 1 ndim Categorical
问题描述
我正在尝试使用来自平面数据的多索引创建数据框。如果三个列表a
、b
和c
, 分别代表数据、日期和名称。
import pandas as pd
import datetime
a = [[0.0, 0.0, 0.0],[0.0, 0.0, 0.0],[0.0, 0.0, 0.0],[0.0, 0.0, 0.0],[0.0, 0.1282051282051282, 0.0],[0.0, 0.05128205128205128, 0.0]]
b = [datetime.datetime(1981, 10, 1, 0, 0),datetime.datetime(1981, 10, 2, 0, 0),datetime.datetime(1981, 10, 3, 0, 0),datetime.datetime(1981, 10, 4, 0, 0),datetime.datetime(1981, 10, 5, 0, 0),datetime.datetime(1981, 10, 6, 0, 0)]
c = [['Ririe Upstream', 'Grays Lake', 'Ririe'],['Ririe Upstream', 'Grays Lake', 'Ririe'],['Ririe Upstream', 'Grays Lake', 'Ririe'],['Ririe Upstream', 'Grays Lake', 'Ririe'],['Ririe Upstream', 'Grays Lake', 'Ririe'],['Ririe Upstream', 'Grays Lake', 'Ririe']]
我发现我可以使用单个日期的索引和名称列表成功地创建具有desried格式的数据框:
idx = pd.MultiIndex.from_product([[b[1]], c[1]], names=['date','name'])
tmp = pd.DataFrame(index=idx, data=a[1],columns=['data'])
返回:
data
date name
1981-10-02 Ririe Upstream 0.0
Grays Lake 0.0
Ririe 0.0
如何使用 和 中的所有数据构建这种格式的数据a
框?b
c
如果我尝试:
idx = pd.MultiIndex.from_product([[b], c], names=['date','name'])
我得到错误:
NotImplementedError: > 1 ndim Categorical are not supported at this time
解决方案
这是另一种方式。
首先,您需要整理数据并使它们的长度相同。
a_new = np.ravel(a)
b_new = np.ravel(np.repeat(b, 3))
c_new = np.ravel(c)
现在我们有 3 个长度相等的列表。接下来我们从 b_new 和 c_new 创建多索引。
idx = pd.MultiIndex.from_tuples(zip(b_new, c_new), names = ('date', 'name'))
最后,我们创建我们的数据框来准确获取您想要的内容。
pd.DataFrame(a_new, index = idx, columns = ['data'])
您的问题pd.MultiIndex.from_product
是 c 在列表中有列表。如果您想使用该功能,您可以执行以下操作:
idx2 = pd.MultiIndex.from_product([b,c[1]], names = ('date','name'))
注意我们只想在 c 中使用 1 个列表,它为我们迭代。
然后:
pd.DataFrame(a_new, index = idx2, columns = ['data'])
这也将为您提供答案。(注意:您仍然需要使用a_new)
推荐阅读
- c++ - 为什么这行得通?c++中的递归str_length函数
- css - Node.js Pug:浏览器不处理 CSS 文件
- c# - WPF 中没有带有 WAV 和 MediaPlayer 的音频
- python - 将旧 dict 列表与新 dict 列表进行比较,以找出所有列表对象的键和值之间的差异
- r - Googlesheets4 不读取我的电子表格
- typescript - 打字稿:将函数参数转换为类型化对象
- r - 在 ggplot2 中调整 rugplot
- html - ASP.NET MVC HTML 如何创建一个更改表单的按钮,而不是提交它
- android - Android - 委托点击的线性布局默认onClickListener?
- python - 重命名 x 刻度 / Seaborn