Skip to main content
 首页 » 编程设计

python之根据列表过滤列表的 Pandas 列

2025年05月04日14lyhabc

有一个大的DataFrame如下:

userid    user_mentions 
1         [2, 3, 4] 
1         [3] 
2         NaN 
2         [1,3] 
3         [1,4,5] 
3         [4] 

user_mentions 列是每个用户提及的 userid 的列表。例如,第一行表示:

用户 1 提到了用户 2、3 和 4。

我需要在 userid 列的用户之间创建一个提及网络。也就是说,我想要 userid 列中的每个用户被 userid 列中的其他用户提及的次数。所以基本上,首先我需要这样的东西:

filtered = df[df['user_mentions'].isin(df['userid'].unique())] 

但这不适用于一列列表。

如果我解决了上述问题,那么我可以groupby['userid','user_mentions']。

编辑

最终输出应该是:

Source    Target    Number 
1         2         1 
1         3         2 
2         1         1 
2         3         1 
3         1         1 
3         5         1 

请您参考如下方法:

这不是一项非常适合 Pandas/NumPy 的任务。所以我建议你使用 collections.defaultdict创建计数字典,然后从字典构建数据框:

from collections import defaultdict 
 
dd = defaultdict(lambda: defaultdict(int)) 
 
for row in df.itertuples(index=False): 
    vals = row.user_mentions 
    if vals == vals: 
        for val in vals: 
            dd[row.userid][val] += 1 
 
df = pd.DataFrame([(k, w, dd[k][w]) for k, v in dd.items() for w in v], 
                  columns=['source', 'target', 'number']) 
 
print(df) 
 
   source  target  number 
0       1       2       1 
1       1       3       2 
2       1       4       1 
3       2       1       1 
4       2       3       1 
5       3       1       1 
6       3       4       2 
7       3       5       1 

当然,您一开始就不应该将列表放在 Pandas 系列中。它是指针的嵌套层,应尽可能避免。