【问题标题】:Insert value to particular instance in dictionary with python使用python将值插入字典中的特定实例
【发布时间】:2021-08-30 06:23:31
【问题描述】:

我想用 for 循环的类实例填充字典,每个实例都有带有消息的列表,如果已经有具有相同 id 的实例,则将消息插入到其列表中。

我正在使用的 csv 文件:

time,ID,TYPE,Source
2021-07-26T23:59:59.143,112233449955,TYPE1,SOURCE1
2021-07-26T23:59:57.146,112233449955,TYPE2,SOURCE3
2021-07-26T23:59:56.148,233445522112,TYPE1,SOURCE2
2021-07-26T23:59:55.120,333333333333,TYPE2,SOURCE2
2021-07-26T23:59:52.130,444444444444,TYPE1,SOURCE14
2021-07-26T23:59:51.132,333333333333,TYPE3,SOURCE4

我的代码:

data = pd.read_csv('data.csv', dtype=str)

df = pd.DataFrame(data, columns=['time', 'ID', 'TYPE', 'Source'])

    class MessageID:
        time = None
        myid = None

    def __init__(self):
        self.messages= []

    class Message:
        time = None
        myid = None
        mytype = None
        source = None

        def __init__(self, time, myid, mytype, source):
            self.time = time
            self.myid = myid
            self.mytype = mytype
            self.source= source


    MessageID_dictionary= {}
    for index, row in df.iterrows():
    
        newMessage = Message(row['time'], row['ID'], row['TYPE'], row['Source'])
    
        # is id already in dictionary? then add newMessage.__dict__ to the list of instance with the found id
        if newMessage.myid in MessageID_dictionary.keys():
            MessageID_dictionary[newMessage.myid] = [MessageID_dictionary[newMessage.myid], newMessage.__dict__]  #Here I do not know how to find the particular instance with the found id (newMessage.id) and append to its list but not directly to the dictionary to the instance of the MessageID's
            print('yes')
        #if there is not the found id then create the instance of MessageID, append the newMessage to list of the instance and add the instance to the dictionary
        else:
            newMessageID = MessageID()
            newMessageID.messages.append(newMessage.__dict__)
            MessageID_dictionary[newMessage.myid] = newMessage.__dict__
            print('no')
    
        print(MessageID.dictionary)
        print(newMessage.messages)

我的问题是,是否有一个选项可以在字典中找到具有指定 id 的特定实例并将值附加到其列表中?

感谢您的帮助!

【问题讨论】:

  • 好的,现在应该没问题了。
  • 您能否也添加一个示例输入和输出
  • 我重新格式化您的代码。核实。您能否使用df.head().to_dict() 的输出更新您的帖子作为您的数据框样本?
  • 我添加了我正在使用的 csv 文件的示例以及我创建并从中填充类属性的 pandas 数据框

标签: python pandas dictionary oop


【解决方案1】:

在 Message 类中有一些我没有得到的东西,比如 Message 类中的 timemiId 字段,但我认为这就是你要找的东西

from collections import defaultdict

import pandas as pd

data = pd.read_csv('data.csv', dtype=str)

df = pd.DataFrame(data, columns=['time', 'ID', 'TYPE', 'Source'])


class MessageID:
    time = None
    myid = None

    def __init__(self):
        self.messages = []


class Message:
    time = None
    myid = None
    mytype = None
    source = None

    def __init__(self, time, myid, mytype, source):
        self.time = time
        self.myid = myid
        self.mytype = mytype
        self.source = source


MessageID_dictionary = defaultdict(MessageID)
for index, row in df.iterrows():

    newMessage = Message(row['time'], row['ID'], row['TYPE'], row['Source'])
    MessageID_dictionary[newMessage.myid].messages.append(newMessage.__dict__)

在此代码的末尾,MessageID_dictionary 将是一个字典,其中键是消息 ID,值是 MessageID 实例,在其 Message 字段中匹配 Message

另外,您可能希望避免使用 iterrows() 并使用它

def create_messageID(group_df):
    new_message = MessageID()
    new_message.messages = group_df.to_dict()
    return new_message

MessageID_dictionary = df.groupby('ID').apply(create_messageID).to_dict()

【讨论】:

    【解决方案2】:

    我认为我找到了我的问题的解决方案,并想在这里分享。如果有更好的方法,请不要犹豫,在这里分享。

    在我上面发布的代码中,我必须添加临时变量,将特定实例存储在字典中定义的位置:

    MessageID_dictionary= {}
    for index, row in df.iterrows():
    
        newMessage = Message(row['time'], row['ID'], row['TYPE'], row['Source'])
    
        # is id already in dictionary? then add newMessage.__dict__ to the list of instance with the found id - so I take the instance with the key that match the id and add to its list the newMessage.__dict__
        if newMessage.myid in MessageID_dictionary.keys():
        tempMsgID = MessageID_dictionary.get(newMessage.myid)
        tempMsgID.messages.append(newMessage.__dict__)
        print('yes')
        #if there is not the found id then create the instance of MessageID, append the newMessage to list of the instance and add the instance to the dictionary
        else:
            newMessageID = MessageID()
            newMessageID.messages.append(newMessage.__dict__)
            MessageID_dictionary[newMessage.myid] = newMessage.__dict__
            print('no')
    
        print(MessageID.dictionary)
        print(newMessage.messages)
    

    【讨论】:

      猜你喜欢
      • 2010-11-05
      • 2010-12-12
      • 2022-10-18
      • 1970-01-01
      • 2022-01-21
      • 2017-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多