gpt4 book ai didi

python - 从组合两个多索引 dfs 和列索引的元组列表构建字典

转载 作者:行者123 更新时间:2023-11-30 22:20:21 26 4
gpt4 key购买 nike

我有两个多索引数据帧:平均值和标准差

arrays = [['A', 'A', 'B', 'B'], ['Z', 'Y', 'X', 'W']]

mean=pd.DataFrame(data={0.0:[np.nan,2.0,3.0,4.0], 60.0: [5.0,np.nan,7.0,8.0], 120.0:[9.0,10.0,np.nan,12.0]},
index=pd.MultiIndex.from_arrays(arrays, names=('id', 'comp')))
mean.columns.name='Times'

std=pd.DataFrame(data={0.0:[10.0,10.0,10.0,10.0], 60.0: [10.0,10.0,10.0,10.0], 120.0:[10.0,10.0,10.0,10.0]},
index=pd.MultiIndex.from_arrays(arrays, names=('id', 'comp')))
std.columns.name='Times'

我的任务是将它们组合在一个字典中,其中“{id:”作为第一级,然后是第二级字典“{comp:”,然后对于每个 comp 一个元组列表,它组合了(时间点,平均值,标准)。 所以,结果应该是这样的:

{'A': {
'Z': [(60.0,5.0,10.0),
(120.0,9.0,10.0)],
'Y': [(0.0,2.0,10.0),
(120.0,10.0,10.0)]
},
'B': {
'X': [(0.0,3.0,10.0),
(60.0,7.0,10.0)],
'W': [(0.0,4.0,10.0),
(60.0,8.0,10.0),
(120.0,12.0,10.0)]
}
}

此外,当数据中存在 NaN 时,三元组将被忽略,因此在时间 0 处取值 A,Z,在时间 60 处取值 A,Y B,在时间 120 处取 X。

我怎样才能到达那里?我已经为单行构建了一个元组列表的字典的字典:

iter=0
{mean.index[iter][0]:{mean.index[iter][1]:list(zip(mean.columns, mean.iloc[iter], std.iloc[iter]))}}
>{'A': {'Z': [(0.0, 1.0, 10.0), (60.0, 5.0, 10.0), (120.0, 9.0, 10.0)]}}

现在,我需要扩展一个字典,在每行 {inner dict) 上循环并添加每个 {outer dict} 的 id。我从 iterrows 和 dic 理解开始,但在这里我遇到了问题,用我从 iterrows() 获得的 iter ('A','Z') 进行索引,并迭代地构建整个字典。

{mean.index[iter[1]]:list(zip(mean.columns, mean.loc[iter[1]], std.loc[iter[1]])) for (iter,row) in mean.iterrows()}

创建错误,我只会有内部循环

KeyError: 'the label [Z] is not in the [index]'

谢谢!

编辑:在这个例子中,我将数字交换为浮点型,因为这里之前生成的整数与我的真实数据不一致,并且在后续的 json 转储中会失败。

最佳答案

这是使用defaultdict的解决方案:

from collections import defaultdict

mean_as_dict = mean.to_dict(orient='index')
std_as_dict = std.to_dict(orient='index')

mean_clean_sorted = {k: sorted([(i, j) for i, j in v.items()]) for k, v in mean_as_dict.items()}
std_clean_sorted = {k: sorted([(i, j) for i, j in v.items()]) for k, v in std_as_dict.items()}

sol = {k: [j + (std_clean_sorted[k][i][1],) for i, j in enumerate(v) if not np.isnan(j[1])] for k, v in mean_clean_sorted.items()}

solution = defaultdict(dict)

for k, v in sol.items():
solution[k[0]][k[1]] = v

生成的字典将是 defaultdict 对象,您可以轻松地将其更改为 dict:

solution = dict(solution)

关于python - 从组合两个多索引 dfs 和列索引的元组列表构建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48864096/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com