python - 字典列表想要获取每个值并将它们放入单独的列表中?

标签 python list dictionary

我的代码的输出如下:

[{'Total Population:': 4585, 'Total Water Ice Cover': 2.848142234497044, 'Total Developed': 17.205368316575324, 'Total Barren Land': 0.22439908514219134, 'Total Forest': 34.40642126612868},

 {'Total Population:': 4751, 'Total Water Ice Cover': 1.047783534830167, 'Total Developed': 37.27115716753022, 'Total Barren Land': 0.11514104778353484, 'Total Forest': 19.11341393206678},

 {'Total Population:': 3214, 'Total Water Ice Cover': 0.09166603009701321, 'Total Developed': 23.50469788404247, 'Total Barren Land': 0.2597204186082041, 'Total Forest': 20.418608204109695},

 {'Total Population:': 5005, 'Total Water Ice Cover': 0.0, 'Total Developed': 66.37545713124746, 'Total Barren Land': 0.0, 'Total Forest': 10.68671271840715},

...
]

我想要做的是获取“总人口”的所有值并将其存储在一个列表中。然后获取所有“总水冰盖”并将其存储在另一个列表中,依此类推。对于这样的数据结构,如何提取这些值并将它们存储到单独的列表中?

谢谢

最佳答案

如果您的目标是calculate Pearson's correlation ,您应该使用 pandas 来实现此目的。

假设您的原始词典列表存储在名为 output 的变量中。您可以使用以下方法轻松将其转换为 pandas DataFrame:

import pandas as pd
df = pd.DataFrame(output)
print(df)
#   Total Barren Land  Total Developed  Total Forest  Total Population:  Total Water Ice Cover
#0           0.224399        17.205368     34.406421               4585               2.848142 
#1           0.115141        37.271157     19.113414               4751               1.047784 
#2           0.259720        23.504698     20.418608               3214               0.091666   
#3           0.000000        66.375457     10.686713               5005               1.047784 

现在您可以轻松生成相关矩阵:

# this is just to make the output print nicer
pd.set_option("precision",4)  # only show 4 digits

# remove 'Total ' from column names to make printing smaller
df.rename(columns=lambda x: x.replace("Total ", ""), inplace=True)  

corr = df.corr(method="pearson")
print(corr)
#                 Barren Land  Developed  Forest  Population:  Water Ice Cover
#Barren Land           1.0000    -0.9579  0.7361      -0.7772           0.4001
#Developed            -0.9579     1.0000 -0.8693       0.5736          -0.6194
#Forest                0.7361    -0.8693  1.0000      -0.1575           0.9114
#Population:          -0.7772     0.5736 -0.1575       1.0000           0.2612
#Water Ice Cover       0.4001    -0.6194  0.9114       0.2612           1.0000

现在您可以通过键访问各个相关性:

print(corr.loc["Forest", "Water Ice Cover"])
#0.91135717479534217

关于python - 字典列表想要获取每个值并将它们放入单独的列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53731864/

相关文章:

python - 如何选择数据框中大于给定值的所有元素

android - 在抽屉导航上出错

c# - 将对象属性值转换为字典

python - 如何在一个 django 模板页面中显示多个 matplotlib 图

python - decision_tree_regressor 模型的负 cross_val_score

python - 在 Python 中,什么时候和什么时候不使用带有 multiprocessing.Pool 的 map() ?输入值较大的情况

c# - C# 遍历列表

python - 从列表创建数据框

java - 如何迭代由 GSON 生成的 JAVA 对象列表

matlab - 在自定义颜色图中显示矩阵中的值 (Matlab)