![](/img/trans.png)
[英]How convert list of dictionaries to a dictionary of dictionaries in Python
[英]How to convert a dictionary with keys of type of tuple to a list of dictionaries in python?
我正在使用pandas
和numpy
库来计算两个简单列表的pearson 相关性。 下面代码的output是相关矩阵:
import numpy as np
import pandas as pd
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y = np.array([2, 1, 4, 5, 8, 12, 18, 25, 96, 48])
x, y = pd.Series(x), pd.Series(y)
xy = pd.DataFrame({'dist-values': x, 'uptime-values': y})
matrix = xy.corr(method="pearson")
在 output 上使用.unstack()
和.to_dict()
函数后,我们可以得到以下格式的字典:
result = matrix.unstack().to_dict()
# {('dist-values', 'dist-values'): 1.0,
# ('dist-values', 'uptime-values'): 0.7586402890911869,
# ('uptime-values', 'dist-values'): 0.7586402890911869,
# ('uptime-values', 'uptime-values'): 1.0}
但我需要将其转换为字典列表,output 应该是这样的:
#[ {'f1': 'dist-values', 'f2': 'dist-values', 'value': '1.0'},
# {'f1': 'dist-values', 'f2': 'uptime-values', 'value': '0.7586402890911869'},
# {'f1': 'uptime-values', 'f2': 'dist-values', 'value': '0.7586402890911869'},
# {'f1': 'uptime-values', 'f2': 'uptime-values', 'value': '1.0'}
# ]
最好和最有效的方法是什么?
关于什么:
result = (matrix.unstack().rename_axis(['f1', 'f2'])
.reset_index(name='value').to_dict('records')
)
output:
[{'f1': 'dist-values', 'f2': 'dist-values', 'value': 1.0},
{'f1': 'dist-values', 'f2': 'uptime-values', 'value': 0.7586402890911869},
{'f1': 'uptime-values', 'f2': 'dist-values', 'value': 0.7586402890911869},
{'f1': 'uptime-values', 'f2': 'uptime-values', 'value': 1.0}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.