首页 > 解决方案 > 如何最好地“扁平化”熊猫中的一对多关系?

问题描述

我目前正在构建异常检测模型。目前,我还在忙于在应用模型之前准备数据。我想将实体分类为异常或不具有以一对多关系关联的信息。我很好奇,它们是否是关于如何将这种关系中的信息输入到表中的最佳实践,其中每一行对应一个实例,然后再输入到模型中。我的方法有效还是有更好的方法?有什么办法可以优化吗?

最初,数据是这样组织的:

每个实例在另一个表中有 N 个关联行。这些行中的每一行对应于已提供的与所讨论的实体相关的对象。每个对象都与一个数量和一个相应的值相关联。请注意,有大量不同的对象可用,并且只有一小部分对象用于与一个实体相关联。

我实现了一种类似于 One-Hot-Encoding 的方法。我为每种可能的对象类型创建了一个功能。然后我遍历包含对象的表,并且对于每一行,我将对象的值添加到目标表中的相应列(相应的对象类型)。

# X Dataframe containing the entity I want to classify
# data Dataframe containing several rows for each entity in X, each row associates the entities of X with a object, its type, quantity and value
target = pd.DataFrame()
#creating a feature for each possible objecttype
for _object in data.objecttype.unique():
    target[_object] = pd.Series(dtype='float64')
#add the id's of all entities
target['id'] = entities.id.unique() 
target.fillna(0.0, inplace=True)
target.set_index('id', inplace=True)

#loop through data table and add the value of each object the the column of the object in the entity table for the entity specified by id
for index, row in data.interrows():
    target.loc[row['id'], row['_objecttype']] = row['value']

代码似乎可以工作,但它的运行时间很糟糕。我也不确定是否有更好的方法来整合这样的信息。

更新: https ://github.com/rubenweinstock/stackoverflow_questions 我添加了 3 个文件,代表我正在处理的数据结构(实体、对象)和结果

标签: pythonpandasone-to-many

解决方案


推荐阅读