“使用pandas DataFrame写入数据时出现“没有’append’属性”错误”

huangapple go评论215阅读模式
英文:

No attribute "append" error while writing data using pandas DataFrame

问题

我遇到以下错误,
AttributeError: 'DataFrame' 对象没有 'append' 属性。你是不是想说: '_append'?

我尝试使用 for 循环将所有设备名称对应的值写入 result_df 变量中的每一行。但是我遇到了没有属性的错误。

我可能漏掉了什么?

可重现的代码:

import pandas as pd
import os
import json

currDir = os.getcwd()

def parse_json_response():
    filename = "my_json_file.json"
    device_name = ["Trona", "Sheldon"]
    "创建用于存储结果的数据框"
    column_names = ["DEVICE", "STATUS", "LAST UPDATED"]
    result_df = pd.DataFrame(columns=column_names)
    my_json_file = currDir + '/' + filename

    for i in range(len(device_name)):
        my_device_name = device_name[i]
        with open(my_json_file) as f:
            data = json.load(f)

        for devices in data:
            device_types = devices['device_types']
            if my_device_name in device_types['name']:
                if device_types['name'] == my_device_name:
                    device = devices['device_types']['name']
                    last_updated = devices['devices']['last_status_update']
                    device_status = devices['devices']['status']

                    result_df = result_df.append(
                        {'DEVICE': device, 'STATUS': device_status,
                         'LAST UPDATED': last_updated}, ignore_index=True)
    print(result_df)

parse_json_response()

这是我的 JSON 文件内容(保存在当前路径中,命名为 "my_json_file.json"):

[
    {"devices": {"id": 34815, "last_status_update": "2023-05-25 07:56:49", "status": "idle" }, "device_types": {"name": "Trona"}},
    {"devices": {"id": 34815, "last_status_update": "2023-05-25 07:56:49", "status": "idle" }, "device_types": {"name": "Sheldon"}}
]
英文:

I am getting below error,
AttributeError: 'DataFrame' object has no attribute 'append'. Did you mean: '_append'?

I am trying to write in result_df variable with all the device name corresponding values on each rows using for loop. But I am getting no attribute error.

what could I possibly be missing here?

Reproducible code:

import pandas as pd
import os
import json

currDir = os.getcwd()
def parse_json_response():

    filename = "my_json_file.json"
    device_name = ["Trona", "Sheldon"]
    "creating dataframe to store result"
    column_names = ["DEVICE", "STATUS", "LAST UPDATED"]
    result_df = pd.DataFrame(columns=column_names)
    my_json_file = currDir + '/' + filename

    for i in range(len(device_name)):
        my_device_name = device_name[i]
        with open(my_json_file) as f:
            data = json.load(f)

        for devices in data:
            device_types = devices['device_types']
            if my_device_name in device_types['name']:
                if device_types['name'] == my_device_name:
                    device = devices['device_types']['name']
                    last_updated = devices['devices']['last_status_update']
                    device_status = devices['devices']['status']

                    result_df = result_df.append(
                      {'DEVICE': device, 'STATUS': device_status,
                     'LAST UPDATED': last_updated}, ignore_index=True)
    print(result_df)

parse_json_response()

Here is my JSON file contents: (save in your current path named as "my_json_file.json")

[{"devices": {"id": 34815, "last_status_update": "2023-05-25 07:56:49", "status": "idle" }, "device_types": {"name": "Trona"}}, {"devices": {"id": 34815, "last_status_update": "2023-05-25 07:56:49", "status": "idle" }, "device_types": {"name": "Sheldon"}}]

答案1

得分: 1

这是您提供的代码的翻译:

尝试这个 -

import pandas as pd
import os
import json

currDir = os.getcwd()
def parse_json_response():

    filename = "my_json_file.json"
    device_name = ["Trona", "Sheldon"]
    "创建数据框以存储结果"
    column_names = ["DEVICE", "STATUS", "LAST UPDATED"]
    result_df = pd.DataFrame(columns=column_names)
    my_json_file = currDir + '/' + filename

    for i in range(len(device_name)):
        my_device_name = device_name[i]
        with open(my_json_file) as f:
            data = json.load(f)

        for devices in data:
            device_types = devices['device_types']
            if my_device_name in device_types['name']:
                if device_types['name'] == my_device_name:
                    device = devices['device_types']['name']
                    last_updated = devices['devices']['last_status_update']
                    device_status = devices['devices']['status']

                    # 一种方式。
                    result_df.loc[len(result_df)] = [device, device_status, last_updated]

                    # 另一种解决方案(更好)
                    result_df = pd.concat([result_df, pd.DataFrame([{'DEVICE': device, 'STATUS': device_status,
                 'LAST UPDATED': last_updated}])], ignore_index=True)

                    # OP的实现
                    # result_df = result_df.append(
                    #   {'DEVICE': device, 'STATUS': device_status,
                    #  'LAST UPDATED': last_updated}, ignore_index=True)
    print(result_df)

parse_json_response()

这个链接帮助我构建了这个解决方案[链接](https://stackoverflow.com/a/75956237/19060733)

请注意,我已经移除了您提供的额外内容并只翻译了代码部分。

英文:

Try this -

import pandas as pd
import os
import json

currDir = os.getcwd()
def parse_json_response():

    filename = "my_json_file.json"
    device_name = ["Trona", "Sheldon"]
    "creating dataframe to store result"
    column_names = ["DEVICE", "STATUS", "LAST UPDATED"]
    result_df = pd.DataFrame(columns=column_names)
    my_json_file = currDir + '/' + filename

    for i in range(len(device_name)):
        my_device_name = device_name[i]
        with open(my_json_file) as f:
            data = json.load(f)

        for devices in data:
            device_types = devices['device_types']
            if my_device_name in device_types['name']:
                if device_types['name'] == my_device_name:
                    device = devices['device_types']['name']
                    last_updated = devices['devices']['last_status_update']
                    device_status = devices['devices']['status']
                    
                    # One way to go.
                    result_df.loc[len(result_df)] = [device, device_status, last_updated]

                    # Another solution (better)
                    result_df = pd.concat([result_df, pd.DataFrame([{'DEVICE': device, 'STATUS': device_status,
                 'LAST UPDATED': last_updated}])], ignore_index=True)

                    # OP's implementation
                    # result_df = result_df.append(
                    #   {'DEVICE': device, 'STATUS': device_status,
                    #  'LAST UPDATED': last_updated}, ignore_index=True)
    print(result_df)

parse_json_response()

This helped me frame the solution.

答案2

得分: 1

以下是您要翻译的内容:

This resolved,

import pandas as pd
import os
import json

currDir = os.getcwd()
def parse_json_response():

    filename = "my_json_file.json"
    device_name = ["Trona", "Sheldon"]
    "creating dataframe to store result"
    column_names = ["DEVICE", "STATUS", "LAST UPDATED"]
    result_df = pd.DataFrame(columns=column_names)
    my_json_file = currDir + '/' + filename

    for i in range(len(device_name)):
        my_device_name = device_name[i]
        with open(my_json_file) as f:
            data = json.load(f)

        for devices in data:
            device_types = devices['device_types']
            if my_device_name in device_types['name']:
                if device_types['name'] == my_device_name:
                    device = devices['device_types']['name']
                    last_updated = devices['devices']['last_status_update']
                    device_status = devices['devices']['status']

                    result_df.loc[len(result_df)] = {'DEVICE': device, 'STATUS': device_status, 'LAST UPDATED': last_updated}
    print(result_df)

parse_json_response()

这是您的JSON文件内容(保存在当前路径并命名为"my_json_file.json"):

[{"devices": {"id": 34815, "last_status_update": "2023-05-25 07:56:49", "status": "idle" }, "device_types": {"name": "Trona"}}, {"devices": {"id": 34815, "last_status_update": "2023-05-25 07:56:49", "status": "idle" }, "device_types": {"name": "Sheldon"}}]
英文:

This resolved,

import pandas as pd
import os
import json

currDir = os.getcwd()
def parse_json_response():

    filename = "my_json_file.json"
    device_name = ["Trona", "Sheldon"]
    "creating dataframe to store result"
    column_names = ["DEVICE", "STATUS", "LAST UPDATED"]
    result_df = pd.DataFrame(columns=column_names)
    my_json_file = currDir + '/' + filename

    for i in range(len(device_name)):
        my_device_name = device_name[i]
        with open(my_json_file) as f:
            data = json.load(f)

        for devices in data:
            device_types = devices['device_types']
            if my_device_name in device_types['name']:
                if device_types['name'] == my_device_name:
                    device = devices['device_types']['name']
                    last_updated = devices['devices']['last_status_update']
                    device_status = devices['devices']['status']

                    result_df.loc[len(result_df)] = {'DEVICE': device, 'STATUS': device_status, 'LAST UPDATED': last_updated}
    print(result_df)

parse_json_response()

Here is my JSON file contents: (save in your current path named as "my_json_file.json")

[{"devices": {"id": 34815, "last_status_update": "2023-05-25 07:56:49", "status": "idle" }, "device_types": {"name": "Trona"}}, {"devices": {"id": 34815, "last_status_update": "2023-05-25 07:56:49", "status": "idle" }, "device_types": {"name": "Sheldon"}}]

huangapple
  • 本文由 发表于 2023年5月26日 11:14:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76337429.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定