首页 > 解决方案 > Python Boto3 列出窗口化数据框中的实例

问题描述

我正在尝试使用 Boto3 在表中列出我的 EC2 实例。

instances = ec2.instances.filter(
    Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
instance_count = sum(1 for _ in instances.all())
RunningInstances = []
for instance in instances:
    id = instance.id
    name = self.get_name_tag(instance)
    type = instance.instance_type
    mylist = {"name":name,"id":id,"type":type}
    RunningInstances.append(mylist.copy())
import numpy as np
import pandas as pd
table = pd.DataFrame.from_dict(RunningInstances)
print(table)

这将创建一个表 - 这太棒了!我的问题是即使列可以适合当前窗口,列也会溢出到另一行:

                 id                                           name  \
0            i-56b243ge                                       My Really Long Name for my Instance
1            i-89b789ga                                       My 2nd Really Long Name for my Instance

                 type
0            t2-micro
1            t2-small

我刚刚得知 Pandas 存在于今天,所以我还没有完全掌握造型。请记住,名称列标题位于名称值的右侧 - 由于 Stack 的格式,我无法将其放在那里。如何将所有数据框/表放入单个视图中?

标签: pythonpandas

解决方案


欢迎来到 Pandas 的世界,你会喜欢它对数据帧执行操作的方式,而不是期望你迭代这些值。我已经改变了你的解析,以展示它的一些能力!

import boto3
import pandas as pd
client=boto3.client('ec2')
response = client.describe_instances()
df=pd.io.json.json_normalize(
    pd.DataFrame(
        pd.DataFrame(
            response['Reservations']
        )\
        .apply(lambda r: r.str[0])\. # Get only the first element of the list
        .Instances\
        .values
        )[0]
    )[['ImageId','InstanceType','Tags']]
df['Name']=df.Tags.apply(lambda r: r[0]['Value']) # Get the name from the tags dict
df.drop(['Tags'], axis=1, inplace=True)
df

会给你:

    ImageId InstanceType Name
0   ami-123 t2.2xlarge   name1
1   ami-234 t2.large     name2
2   ami-345 m5.12xlarge  name3

推荐阅读