【问题标题】:Creating a column of edges创建一列边
【发布时间】:2021-07-05 18:45:06
【问题描述】:

我需要将uids 列中的一个uid 连接到friends 列列表中的每个uid,如下例所示:

给定一个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'] 部分对我来说有点麻烦,所以我想知道是否有更简单的方法来完成这项任务?

提前致谢。

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    为什么不试试product

    import itertools
    A['in_edges'] = A.apply(lambda x : [*itertools.product([x['uid']], x['friends'])],axis=1)
    A
    Out[50]: 
       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)]
    

    【讨论】:

      【解决方案2】:

      您可以将.apply()axis=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)]
      

      【讨论】:

      • 您的解决方案的一个问题是使用.loc[] 在性能方面比标准[] 运算符要好得多。有没有办法在您的解决方案中使用 .loc[] 运算符?
      • @MichaelSidoroff 你可以使用df.loc[:, ["uid", "friends"]].apply(...),但我不明白这一点。
      • [] 的性能可能比使用.loc[] 的相同实现差三倍,如下所示:stackoverflow.com/a/65875826/4596078
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      相关资源
      最近更新 更多