熊猫-通过基于两列中的ID链接多个行来将消息分组为会话

时间:2019-03-14 01:20:50

标签: python pandas dataframe

我有一些数据可根据source_id和response_id跟踪推文和响应。 source_id可以与原始帖子或具有自己响应的响应关联。如果有多个响应,则每个响应将具有一个source_id,并且该source_id将出现在相应响应的response_id中。

以该数据框为例:

df = pd.DataFrame({
'date': ['2018-10-02', '2018-10-03', '2018-10-03', '2018-10-03', '2018-10-03', '2018-10-03', '2018-10-03', '2018-10-03', '2018-10-03'],
'id': ['334', '335', '336', '337', '338', '340', '341', '343', '358'],
'source_id': ['830', '636', '657', '569', '152', '975', '984', '720', '524'],
'reply_id': [np.nan, '495', '636', '657', '569', '830', '152', np.nan, np.nan]
})

及其输出:

         date   id source_id reply_id
0  2018-10-02  334       830      NaN
1  2018-10-03  335       636      495
2  2018-10-03  336       657      636
3  2018-10-03  337       569      657
4  2018-10-03  338       152      569
5  2018-10-03  340       975      830
6  2018-10-03  341       984      152
7  2018-10-03  343       720      NaN
8  2018-10-03  358       524      NaN

每行包含一条消息的数据。无论是推文还是对推文的响应,消息都有唯一的ID。在此示例中,有两个“对话”,一个或多个对原始帖子的回复,以及两个独立的推文,没有回复。没有响应的推文为df.iloc[7]df.iloc[8],它们的reply_id中都包含NaN,并且它们的source_id不出现在任何其他行的reply_id中。 df.iloc[0]的reply_id中包含NaN,而其source_id显示在df.iloc[5]的reply_id中。这样就算是一次对话。

我真正想做的是如何将一系列{@ {1}},df.iloc[1]df.iloc[2]df.iloc[3]和{{ 1}},并将所有内容计为一次对话。对于此特定对话,原始帖子没有可用数据,因此没有source_id = 495的行。

有人对如何解决这个问题有任何想法吗?

1 个答案:

答案 0 :(得分:1)

据我了解,这更像是网络问题,因此我们使用networkx

import networkx as nx 
G=nx.from_pandas_edgelist(df.dropna(), 'reply_id', 'source_id')
l=list(nx.connected_components(G))
newdf=pd.DataFrame(l)
newdf
Out[334]: 
     0    1     2     3     4     5
0  975  830  None  None  None  None
1  984  495   636   152   569   657 
# here you saw all the value belong to one group, they are in the same line 

更多详细信息,现在同一组索引将具有相同的ID

d=[dict.fromkeys(y,x)for x , y in enumerate(list(nx.connected_components(G)))]
d={k:v for element in d for k,v in element.items()}
ids=df.reply_id.dropna().map(d)
ids
Out[344]: 
1    1
2    1
3    1
4    1
5    0
6    1
Name: reply_id, dtype: int64