Pandas数据帧到字典,元组作为键和值

2024-09-30 08:28:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助完成以下工作:

df文件作为一个CSV文件加载到下面的帧中。有多个区域,内存、vCPU和存储器的值与每个“名称”相对应。此数据帧中有1700行。在

The dataframe with the CSV values loaded in

我需要创建一个包含以下内容的词典:

Key是一个包含两个元素的元组:Name和Region

字典的价值是一个元组:Windows按需成本和Linux按需成本

最后,我想创建一个程序,它执行以下操作: 用户输入一个特定的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

Tags: 文件名称linuxwindows存储器generalushourly
2条回答

这是创建字典的部分

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)

我会试试这样的方法:

outdict = {k: (gdf['Windows On Demand cost'].item(), 
               gdf['Linux On Demand cost'].item())
           for k, gdf in df.groupby(['Name', 'Region'])}

相关问题 更多 >

    热门问题