首页 > 解决方案 > Pandas DataFrame 到以元组为键和值的字典

问题描述

我需要帮助执行以下操作:

我有一个如下的 CSV 文件,加载到数据框“df”中。有多个区域,对应于每个“名称”的内存、vCPU 和存储的值不同。此数据框中有 1700 行。

加载了 CSV 值的数据框

我需要创建一个具有以下内容的字典:

键是一个包含两个元素的元组:名称和区域

字典的值是一个元组:Windows On-demand cost 和 Linux On-demand cost

最终,我想创建一个程序,它执行以下操作:用户输入某个 CPU 和 Ram 和存储,该程序将对数据进行排序并提取名称,以及该处理器的 Windows 和 Linux 价格(如果有)匹配,或者如果不匹配,会将处理器拉到最接近输入值的位置。谢谢!

Name    Region  API Memory  vCPUs   Storage Linux   Windows
0   M1 General Purpose Small    US West - NorCal    m1.small    1.7 GiB 1 vCPUs 160 GiB $0.047000 hourly    $0.078000 hourly
1   M1 General Purpose Medium   US West - NorCal    m1.medium   3.75 GiB    1 vCPUs 410 GiB $0.095000 hourly    $0.157000 hourly
2   M1 General Purpose Large    US West - NorCal    m1.large    7.5 GiB 2 vCPUs 840 GiB $0.190000 hourly    $0.314000 hourly
3   M1 General Purpose Extra Large  US West - NorCal    m1.xlarge   15.0 GiB    4 vCPUs 1680 GiB    $0.379000 hourly    $0.627000 hourly
4   C1 High-CPU Medium  US West - NorCal    c1.medium   1.7 GiB 2 vCPUs 350 GiB $0.148000 hourly    $0.228000 hourly

标签: pythonpandasdictionarydataframe

解决方案


这是创建字典的部分

tempDict = {}

for i in df.index:

    key = (df.at[i, 'Name'] ,df.at[i, 'Region']) #Rename columns accordingly
    value = (df.at[i, 'Windows On-demand cost'] ,df.at[i, 'Linux On demand cost']) #Rename columns accordingly

    dictionary = {key: value}
    tempDict.update(dictionary)

print(tempDict)

推荐阅读