首页 > 解决方案 > 如何规范化特征工具中一个特征具有多个值的实体?

问题描述

下面是一个例子:

buy_log_df = pd.DataFrame(
    [
        ["2020-01-02", 0, 1, 2, 2],
        ["2020-01-02", 1, 1, 1, 3],
        ["2020-01-02", 2, 2, 1, 1],
        ["2020-01-02", 3, 3, 3, 1],
    ],
    columns=['date', 'sale_id', 'customer_id', "item_id", "quantity"]
)

item_df = pd.DataFrame(
    [
        [1, 100],
        [2, 200],
        [3, 300],
    ],
    columns=['item_id', 'price']
)

item_df2 = pd.DataFrame(
    [
        [1, '1 3 10'],
        [2, '1 3'],
        [3, '2 5'],
    ],
    columns=['item_id', 'tags']
)

正如您在此处看到的,其中的每个项目都item_df具有多个标签值作为一个特征。

这是我尝试过的:

item_df2 = pd.concat([item_df2, item_df2['tags'].str.split(expand=True)], axis=1)
item_df2 = pd.melt(
    item_df2,
    id_vars=['item_id'],
    value_vars=[0,1,2],
    value_name="tags"
)
tag_log_df = item_df2[item_df2['tags'].notna()].drop("variable", axis=1,).sort_values("item_id")
tag_log_df

>>>

   item_id tags
0        1    1
3        1    3
6        1   10
1        2    1
4        2    3
2        3    2
5        3    5

看起来我无法规范化这个 item 实体(来自 buy_log 实体),因为它item_id在表中有多个重复的 s。

设计实体集时如何处理这种情况?

标签: featuretools

解决方案


谢谢你的问题。要处理多个标签值,您可以在构建实体集之前将标签规范化为数据框。

buy_log_df

       date  sale_id  customer_id  item_id  quantity
 2020-01-02        0            1        2         2
 2020-01-02        1            1        1         3
 2020-01-02        2            2        1         1
 2020-01-02        3            3        3         1

item_df

 item_id  price
       1    100
       2    200
       3    300

tag_log_df

 item_id tags
       1    1
       1    3
       1   10
       2    1
       2    3
       3    2
       3    5

使用标准化数据,您可以构建实体集。

es = ft.EntitySet()

es.entity_from_dataframe(
    entity_id='buy_log',
    dataframe=buy_log_df,
    index='sale_id',
    time_index='date',
)

es.entity_from_dataframe(
    entity_id='item',
    dataframe=item_df,
    index='item_id',
)

es.entity_from_dataframe(
    entity_id='tag_log',
    dataframe=tag_log_df,
    index='tag_log_id',
    make_index=True,
)

parent = es['item']['item_id']
child = es['buy_log']['item_id']
es.add_relationship(ft.Relationship(parent, child))

child = es['tag_log']['item_id']
es.add_relationship(ft.Relationship(parent, child))

在此处输入图像描述


推荐阅读