首页 > 解决方案 > pandas:construct dataframe with > 1 ndim Categorical

问题描述

我正在尝试使用来自平面数据的多索引创建数据框。如果三个列表abc, 分别代表数据、日期和名称。

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框?bc

如果我尝试:

idx = pd.MultiIndex.from_product([[b], c], names=['date','name'])

我得到错误:

NotImplementedError: > 1 ndim Categorical are not supported at this time

标签: pythonpandas

解决方案


这是另一种方式。

首先,您需要整理数据并使它们的长度相同。

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


推荐阅读