[英]How to convert a dictionary with keys of type of tuple to a list of dictionaries in python?
I am using pandas
and numpy
libraries, to calculate the pearson correlation of two simple lists.我正在使用
pandas
和numpy
库来计算两个简单列表的pearson 相关性。 The output of the below code is the matrix of correlation:下面代码的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")
After using the .unstack()
, and .to_dict()
functions on the output we can have a dictionary in the below format:在 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}
But I need to convert it to a list of dictionaries, and the output should be like this:但我需要将其转换为字典列表,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'}
# ]
What's the best and efficient way to do it?最好和最有效的方法是什么?
What about:关于什么:
result = (matrix.unstack().rename_axis(['f1', 'f2'])
.reset_index(name='value').to_dict('records')
)
output: 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.