[英]Fill pandas dataframe within a for loop
我正在与 Amazon Rekognition 合作进行一些图像分析。 使用简单的 Python 脚本,我在每次迭代中都会得到这种类型的响应:(例如,猫的图像)
{'Labels':
[{'Name': 'Pet', 'Confidence': 96.146484375, 'Instances': [],
'Parents': [{'Name': 'Animal'}]}, {'Name': 'Mammal', 'Confidence': 96.146484375,
'Instances': [], 'Parents': [{'Name': 'Animal'}]},
{'Name': 'Cat', 'Confidence': 96.146484375.....
我在列表中获得了我需要的所有属性,如下所示:
[Pet, Mammal, Cat, Animal, Manx, Abyssinian, Furniture, Kitten, Couch]
现在,我想创建一个数据框,其中上面列表中的元素显示为列,而行的值为 0 或 1。
我创建了一个字典,在其中添加列表中的元素,所以我得到 {'Cat': 1},然后我将它添加到数据帧中,我得到以下错误: TypeError : Index(...) must被称为某种集合,“猫”被传递了。
不仅如此,我什至似乎无法将来自不同图像的信息添加到同一个数据框中。 例如,如果我只在数据框中插入数据(作为行,而不是列),我会得到一个包含 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', 'Confidence': 96.146484375, '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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.