向投影图中的边添加属性

2024-03-29 13:09:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似于隶属矩阵的数据帧。我有一个人,一个事件和事件的年份。你知道吗

d = {'person' : ['1', '2', '3', '1', '4', '3', '4', '1', '2'],
    'event' : ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D'],
    'year' : [1995, 1995, 1995, 1996, 1996, 2000, 2000, 2001, 2001]}

df = pd.DataFrame(d)

我需要两个人第一次见面。也就是说,如果“1”和“2”在事件“A”和“D”中相遇,我需要知道他们第一次见面的时间(在这个例子中,是在1995年的“A”中)。你知道吗

我不知道这是否可以使用NetworkX,或者我是否需要用其他方式使用Pandas。我该怎么做?你知道吗

我可以到达投影网络,但我不知道如何将属性'year'转移到投影网络的边缘。需要注意的是,属性(在本例中为“年”)是事件的一个属性,因此它对于每个事件的所有边都是常量。你知道吗

到目前为止,我的情况是:

import networkx as nx
import pandas as pd

d = {'person' : ['1', '2', '3', '1', '4', '3', '4', '1', '2'],
     'event' : ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D'],
     'year' : [1995, 1995, 1995, 1996, 1996, 2000, 2000, 2001, 2001]}

df = pd.DataFrame(d)

B = nx.from_pandas_dataframe(df, 'person', 'event', edge_attr='year')

G = nx.bipartite.projected_graph(B, df.person.unique(), multigraph = True)

Tags: import网络eventdataframepandasdf属性as
1条回答
网友
1楼 · 发布于 2024-03-29 13:09:15

我对NetworkX还不够熟悉,无法帮助您解决添加边属性的问题,但这种方法确实可以识别个人的第一次会面。你知道吗

import pandas as pd
import itertools

# initial data
d = {'person' : ['1', '2', '3', '1', '4', '3', '4', '1', '2'],
     'event' : ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D'],
     'year' : [1995, 1995, 1995, 1996, 1996, 2000, 2000, 2001, 2001]}

df = pd.DataFrame(d)

# create a unique list of individuals for each meeting. this should be
# unique anyway, but just in case. :)
# note that this approach is also robust to events in different years
# sharing the same name.

grpd = df.groupby(['year', 'event'])['person'].unique().apply(lambda x: sorted(x))

# sort based on the year from the oldest meetings to the most recent
grpd.sort_index(ascending=False, inplace=True)

# we'll add meetings to a dictionary and overwrite as encounter more
# recent meetings

meetings = {}

for idx in range(len(grpd)):
    year = grpd.index[idx][0]
    meeting = grpd.index[idx][1]
    for combo in itertools.combinations(grpd[idx], 2):
        meetings[combo] = (meeting, year)


import pprint

>>> pprint.pprint(meetings)
{('1', '2'): ('A', 1995),
 ('1', '3'): ('A', 1995),
 ('1', '4'): ('B', 1996),
 ('2', '3'): ('A', 1995),
 ('3', '4'): ('C', 2000)

相关问题 更多 >