如何解决在for循环内填充熊猫数据框
我正在与Amazon Rekognition合作进行一些图像分析。 使用简单的Python脚本,每次迭代都会得到以下类型的响应: (例如猫的图像的示例)
{'Labels':
[{'Name': 'Pet','Confidence': 96.146484375,'Instances': [],'Parents': [{'Name': 'Animal'}]},{'Name': 'Mammal',{'Name': 'Cat','Confidence': 96.146484375.....
我在列表中获得了所需的所有属性,如下所示:
[Pet,Mammal,Cat,Animal,Manx,Abyssinian,Furniture,Kitten,Couch]
现在,我想创建一个数据框,其中上面列表中的元素显示为列,而行取值为0或1。
我创建了一个字典,在其中添加了列表中的元素,因此得到了{'Cat':1},然后将其添加到数据帧中并出现以下错误: TypeError :必须使用某种类型的集合来调用Index(...),并且已传递“ Cat”。
不仅如此,但我似乎甚至无法将来自不同图像的信息添加到同一数据框中。例如,如果我仅将数据插入数据框中(作为行,而不是列),则会得到一个包含n行的序列,其中n个元素(由Amazon Rekognition标识)的仅最后一张图像,即我在每次迭代时都从一个空的数据帧开始。 我想得到的结果是这样的:
Image Human Animal Flowers etc...
Pic1 1 0 0
Pic2 0 0 1
Pic3 1 1 0
作为参考,这是我现在正在使用的代码(我应该补充一点,我正在开发一个名为KNIME的软件,但这只是Python):
from pandas import DataFrame
import pandas as pd
import boto3
fileName=flow_variables['Path_Arr[1]'] #This is just to tell Amazon the name of the image
bucket= 'mybucket'
client=boto3.client('rekognition',region_name = 'us-east-2')
response = client.detect_labels(Image={'S3Object':
{'Bucket':bucket,'Name':fileName}})
data = [str(response)] # This is what I inserted in the first cell of this question
d= {}
for key,value in response.items():
for el in value:
if isinstance(el,dict):
for k,v in el.items():
if k == "Name":
d[v] = 1
print(d)
df = pd.DataFrame(d,ignore_index=True)
print(df)
output_table = df
在for循环中以及向我的数据帧添加内容时,我肯定都错了,但是似乎没有任何作用!
对于超长问题,我们深表歉意!有什么想法吗?
解决方法
我不知道这是否可以完全回答您的问题,因为我不知道您的数据看起来像什么,但是我认为这是一个应该对您有所帮助的好步骤。我多次添加了相同的数据,但是方法应该很清楚。
import pandas as pd
response = {'Labels': [{'Name': 'Pet','Confidence': 96.146484375,'Instances': [],'Parents': [{'Name': 'Animal'}]},{'Name': 'Cat','Instances': [{'BoundingBox':
{'Width': 0.6686800122261047,'Height': 0.9005332589149475,'Left': 0.27255237102508545,'Top': 0.03728689253330231},'Confidence': 96.146484375}],'Parents': [{'Name': 'Pet'}]
}]}
def handle_new_data(repsonse_data: dict,image_name: str) -> pd.DataFrame:
d = {"Image": image_name}
result = pd.DataFrame()
for key,value in repsonse_data.items():
for el in value:
if isinstance(el,dict):
for k,v in el.items():
if k == "Name":
d[v] = 1
result = result.append(d,ignore_index=True)
return result
df_all = pd.DataFrame()
df_all = df_all.append(handle_new_data(response,"image1"))
df_all = df_all.append(handle_new_data(response,"image2"))
df_all = df_all.append(handle_new_data(response,"image3"))
df_all = df_all.append(handle_new_data(response,"image4"))
df_all.reset_index(inplace=True)
print(df_all)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。