python-3.x - 创建一列边
问题描述
我需要将列中的 uid 连接到uids
列列表中的每个 uid,friends
如下例所示:
给定一个pandas.DataFrame
对象A
:
uid friends
0 1 [10, 2, 1, 5]
1 2 [1, 2]
2 3 [5, 4]
3 4 [10, 5]
4 5 [1, 2, 5]
所需的输出是:
uid friends in_edges
0 1 [10, 2, 1, 5] [(1, 10), (1, 2), (1, 1), (1, 5)]
1 2 [1, 2] [(2, 1), (2, 2)]
2 3 [5, 4] [(3, 5), (3, 4)]
3 4 [10, 5] [(4, 10), (4, 5)]
4 5 [1, 2, 5] [(5, 1), (5, 2), (5, 5)]
我使用以下代码来实现此结果:
import numpy as np
import pandas as pd
A = pd.DataFrame(dict(uid=[1, 2, 3, 4, 5], friends=[[10, 2, 1, 5], [1, 2], [5, 4], [10, 5], [1, 2, 5]]))
A.loc[:, 'in_edges'] = A.loc[:, 'uid'].apply(lambda uid: [(uid, f) for f in A.loc[A.loc[:, 'uid']==uid, 'friends'].values[0]])
但这A.loc[A.loc[:, 'uid']==uid, 'friends']
部分对我来说看起来有点麻烦,所以我想知道是否有更简单的方法来完成这项任务?
提前致谢。
解决方案
您可以使用.apply()
withaxis=1
参数:
df["in_edges"] = df[["uid", "friends"]].apply(
lambda x: [(x["uid"], f) for f in x["friends"]], axis=1
)
print(df)
印刷:
uid friends in_edges
0 1 [10, 2, 1, 5] [(1, 10), (1, 2), (1, 1), (1, 5)]
1 2 [1, 2] [(2, 1), (2, 2)]
2 3 [5, 4] [(3, 5), (3, 4)]
3 4 [10, 5] [(4, 10), (4, 5)]
4 5 [1, 2, 5] [(5, 1), (5, 2), (5, 5)]
推荐阅读
- typescript - 是的,条件验证和 TypeScript
- unity3d - HLSL 奇怪的行为加/减小数字
- python - 在 django 中为一个特殊的 url 获取 Cross-Origin Request Blocked 错误
- rust - 如何在闭包中使用 FnMut 参数而不移动它或需要复制?
- python - 递归查找变量
- android - Android:fireStore 将可映射数组转换为对象的问题
- linux - client_loop:发送断开连接:DM 服务器上的管道损坏
- android - Mixpanel:OptinTracking 用户删除配置文件属性(退出后)
- apache-spark - 如何在另一个 DF 的列中获取 DF 的一列中的值的计数?
- ruby-on-rails - Rails React 部署到 Heroku 时无法渲染 CSS