我正在尝试从平面数据创建一个具有多索引的数据框。如果有三个列表 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']]
我发现我可以使用单个日期和名称列表的索引成功创建具有所需格式的数据框:
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)
关于python - pandas:使用 > 1 ndim 分类构造数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57332959/