featuretools - 如何规范化特征工具中一个特征具有多个值的实体?
问题描述
下面是一个例子:
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。
设计实体集时如何处理这种情况?
解决方案
谢谢你的问题。要处理多个标签值,您可以在构建实体集之前将标签规范化为数据框。
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))
推荐阅读
- python - 如何从@commands.has_role() 获取“错误”消息
- sql-server - MS SQL Server:防止执行计划过时
- javascript - 客户端使用 CryptoJS 计算的 MD5 哈希与终端计算不同
- javascript - JavaScript 函数未发布
- mysql - 找出所有与克里斯托弗·诺兰合作的电影比其他任何导演都多的演员
- microservices - 在具有事件源的微服务中,我应该将命令或事件保存到服务数据库还是应该是一个大数据库?
- octobercms - 如何使用 OctoberCms 回滚?
- python - 从数据框列值创建一个函数并插入另一列的空白元素
- docker - Docker-compose 与所有其他容器一起运行容器
- python - TypeError: verify_file() got an unexpected keyword argument 'data_filename' (GNUPG)