【问题标题】:Fill pandas dataframe within a for loop在 for 循环中填充熊猫数据框
【发布时间】:2020-09-30 17:12:43
【问题描述】:

我正在使用 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(...),传递了“Cat”。

不仅如此,我什至无法将来自不同图像的信息添加到同一个数据框中。例如,如果我只在数据框中插入数据(作为行,而不是列),我会得到一个包含 n 行的系列,其中包含 only 最后一张图像的 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 循环和向我的数据框中添加内容时,我肯定都弄错了,但似乎没有任何效果!

很抱歉这个超长的问题,希望它很清楚!有什么想法吗?

【问题讨论】:

  • 您能否展示您正在处理的示例响应(您的第二条评论在哪里)?
  • @D-E-N 抱歉,我不确定我是否理解您的问题,但我从“data = [str(response)]”得到的是 ["{'Labels': [{'Name' :'宠物','信心':96.146484375,'实例':[],'父母':[{'名称':'动物'}]},{'名称':'猫','信心':96.146484375, '实例':[{'界限':{'宽度':0.6686800122261047,'高度':0.9005332589149475,“左”:0.27255237102508545,'上面':0.03728689253330231},'信心':96.146484375}],'父母':[父母':[父母':[父母':[ '名称':'宠物'},..."]

标签: python dataframe for-loop image-recognition knime


【解决方案1】:

我不知道这是否完全回答了你的问题,因为我不知道你的数据是什么样的,但我认为这是一个很好的步骤,应该可以帮助你。我多次添加相同的数据,但方式应该清楚。

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 2019-10-05
    • 2022-01-08
    • 2015-03-19
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    相关资源
    最近更新 更多