python - 如何在 pandas 中的列之间建立关系?
问题描述
我有一个来自 LASTFM 数据集的数据框,其中包含以下列: user_id | 像这样的friend_id:
uid | fid
346 | 23
355 | 48
我想将用户之间的关系作为第三列(一种邻接向量),例如:
uid1 | uid2 | friends
23 | 48 | 0
23 | 56 | 0
23 | .. | 0
23 | 346 | 1
48 | 23 | 0
48 | 56 | 0
48 | .. | 0
48 | 346 | 0
48 | 355 | 1
23 | .. | 0
23 | 346 | 1
346 | 23 | 1
我尝试过使用合并、加入、lambda,但到目前为止都没有成功。任何帮助,将不胜感激。
解决方案
这里的策略是两步。首先创建 UID 叉积数据集,然后附加好友指标:
通过首先从原始数据集中获取对的并集以及它们的逆来创建 UID 叉积。我们将创建一个中间数据集 ,friends
我们将在稍后的过程中使用它来指示哪些 UID 是朋友:
pairs = df.rename(columns={'uid': 'uid1', 'fid': 'uid2'})
friends = pd.concat([pairs, pairs.rename(columns={'uid1': 'uid2', 'uid2':'uid1'})])
uids = friends.uid1.drop_duplicates().to_frame(name='uid')
uid
0 346
1 355
0 23
1 48
然后,附加一个虚拟合并键以允许交叉产品合并:
uids['dummy_key'] = 1
uids = uids.merge(uids, on='dummy_key', suffixes=('1', '2'))[['uid1', 'uid2']]
uid1 uid2
0 346 346
1 346 355
2 346 23
3 346 48
4 355 346
5 355 355
...
现在,我们合并朋友数据集,附加一个指示列,开始我们的邻接列表:
adj = uids.merge(friends, on=['uid1', 'uid2'], how='left', indicator=True)
uid1 uid2 _merge
0 346 346 left_only
1 346 355 left_only
2 346 23 both
3 346 48 left_only
4 355 346 left_only
5 355 355 left_only
...
最后,我们将_merge
指标编码到friend
列中:
adj['friends'] = adj.apply(lambda row: 1 if row['_merge'] == 'both' else 0, axis=1)
adj = adj[['uid1', 'uid2', 'friends']]
uid1 uid2 friends
0 346 346 0
1 346 355 0
2 346 23 1
3 346 48 0
4 355 346 0
5 355 355 0
推荐阅读
- python - AttributeError:模块“tensorflow.compat.v2.summary”没有属性“标量”
- spring-boot - 谷歌云 Spring Boot NoSuchFileException
- python - 如何在每台服务器中仅向 1 个文本通道发送消息
- python - ACM 在 Lambda 函数中描述证书并获取 DomainValidationOptions 的值
- ajax - 使用 jQuery Ajax 在本地使用和托管 Web Api
- python - Django - 按类别查询属于目标的帖子?
- javascript - Angular 8 this.router.navigate() 更改 URL 但不呈现到下一页
- python - 如何在pygame中设置枪的射击速度/枪的射速
- python - 当两种方法都在同一个类中时,如何使在一种方法中定义的列表在另一种方法中可用?
- php - 为什么我不能在 PHP 类的嵌套数组中附加元素?