gpt4 book ai didi

python - pandas - 根据列值将数据框 reshape 为边缘列表

转载 作者:行者123 更新时间:2023-12-01 04:09:58 25 4
gpt4 key购买 nike

从这个简单的数据框开始:

  node   t1   t2
0 a pos neg
1 b neg neg
2 c neg neg
3 d pos neg
4 e neg pos
5 f pos neg
6 g neg pos

我想构建一个边缘列表文件以将其作为无向网络读取。预期输出为:

b c
a d
a f
d f
e g

所以基本上,如果两个节点在 ['t1','t2'] 列中具有相同的值对,我就会链接它们。到目前为止,我首先尝试将这些值分组到一个新列中:

d['c'] = [tuple(i) for i in df[['t1','t2']].values]

但是我却坚持按照自己的意愿对用户进行分组。

编辑:修复创建新列时的错误。

最佳答案

看看这个:

df = pd.DataFrame({'node': ['a', 'b','c', 'd', 'e', 'f', 'g'],
't1': ['pos', 'neg', 'neg', 'pos', 'neg', 'pos', 'neg'],
't2': ['neg', 'neg', 'neg', 'neg', 'pos', 'neg', 'pos']})

K = nx.Graph()
K.add_nodes_from(df['node'].values)

# Create edges
for i, group in df.groupby(['t1', 't2'])['node']:
# generate all combinations without replacement
# from the group of similar column pairs
for u, v in itertools.combinations(group, 2):
K.add_edge(u, v)

print(K.edges())

Result: [('a', 'd'), ('a', 'f'), ('c', 'b'), ('e', 'g'), ('d', 'f')]

这里的技巧是在 pandas 中同时按 2 列进行分组。然后,您可以创建要添加到图中的所有边组合。

关于python - pandas - 根据列值将数据框 reshape 为边缘列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35089255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com