【问题标题】:Pandas: create column id based on intersections on rowsPandas:根据行上的交叉点创建列 ID
【发布时间】:2021-02-17 09:34:25
【问题描述】:

我有一个 pandas DataFrame 如下:

id1 id2 id3
a x u
a y j
b x t
c z r
d p r

我需要创建一个新的列 ID,考虑到列 id1、id2 和 id3 中的值之间的所有交集。

需要的输出如下:

id1 id2 id3 ID
a x u 1
a y j 1
b x t 1
c z r 2
d p r 2

  • ID=1 考虑 id1:[a,b],id2:[x,y],id3:[u,j,t]
  • ID=2 考虑到 id1: [c,d], id2: [z,p], id3: [r]

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用DataFrame.melt 进行反透视,以便可能将2 列传递给convert_matrix.from_pandas_edgelist,并获取所有connected_components 用于字典,最后使用Series.map 用于新列:

    df1 = df.melt(id_vars='id1', value_vars=['id2','id3'])
    
    import networkx as nx
    
    # Create the graph from the dataframe
    g = nx.Graph()
    g = nx.from_pandas_edgelist(df1,'id1','value')
    
    connected_components = nx.connected_components(g)
    
    # Find the component id of the nodes
    node2id = {}
    for cid, component in enumerate(connected_components):
        for node in component:
            node2id[node] = cid + 1
    
    df['g'] = df['id1'].map(node2id)
    print (df)
      id1 id2 id3  g
    0   a   x   u  1
    1   a   y   j  1
    2   b   x   t  1
    3   c   z   r  2
    4   d   p   r  2
    

    【讨论】:

      猜你喜欢
      • 2020-08-03
      • 2021-10-12
      • 2020-08-18
      • 1970-01-01
      • 2021-01-02
      • 2021-08-27
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多