python - 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 的格式,我无法将其放在那里。如何将所有数据框/表放入单个视图中?
解决方案
欢迎来到 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
推荐阅读
- rust - 为什么某些命令在 TMUX 中不起作用?
- neo4j - Neo4j ETL 从 RDBMS 迁移到 Graph 需要时间
- r - 如何将行值转换为 R 中的单个字符串?
- python - 不能在Python中划分两个字典
- java - 如何解决 Swagger UI 中的 500 Internal Server Error,服务未运行
- javascript - 避免在它消失之前再次单击html按钮(django)
- python - 从 Cloud Function 调用 Document AI v1beta3 时权限被拒绝
- python - 如何从字典键的前面删除多余的空间?
- reactjs - 如何在 NextJS 中制作小部件
- javascript - 应用程序在服务器上时如何修改应用程序内容(构建后)