Python Boto3在数据帧窗口中列出实例

2024-09-25 08:39:39 发布

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

我试图用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)
<>这太好了!我的问题是列溢出到另一行,即使列可以容纳在当前窗口中:

^{pr2}$

我刚知道熊猫现在还存在,所以我还没有完全掌握造型。请记住,name列标题位于name值的右侧-我不能将其放在那里,因为Stack的格式。如何将所有的数据帧/表放入一个视图中?在


Tags: instancesinstancenameinimportidforas
1条回答
网友
1楼 · 发布于 2024-09-25 08:39:39

欢迎来到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

会给你:

^{pr2}$

相关问题 更多 >