gpt4 book ai didi

python - 从 pandas 数据帧生成边缘列表

转载 作者:太空宇宙 更新时间:2023-11-03 15:37:03 25 4
gpt4 key购买 nike

假设我有一个像这样的 pandas 数据框:

    Fruit_1   Fruit_2  Fruit_3 
0 Apple Orange Peach
1 Apple Lemon Lime
2 Starfruit Apple Orange

可复制的形式:

df = pd.DataFrame([['Apple', 'Orange', 'Peach'],
['Apple', 'Lemon', 'Lime'],
['Starfruit', 'Apple', 'Orange']],
columns=['Fruit_1', 'Fruit_2', 'Fruit_3'])

我想生成一个边缘列表,其中包含:

Apple, Orange
Apple, Peach
Orange, Peach
Apple, Lemon
Apple, Lime
Lemon, Lime
Starfruit, Apple
Starfruit, Orange
Apple, Orange

如何在 Python 中执行此操作?

最佳答案

我不知道 pandas,但你可以在行上使用 itertools.combinations

itertools.combinations(row, 2)

这会创建一个迭代器,您可以简单地将其转换为对列表。

将这些列表收集到列表中后加入这些列表可以使用平面列表理解来完成

[pair for row in collected_rows for pair in row]

或者使用通常更快的numpy方式

data[:, np.c_[np.tril_indices(data.shape[1], -1)]]

如果你想要一个扁平的列表

data[:, np.c_[np.triu_indices(data.shape[1], 1)]].reshape(-1,2)

请注意,triu_indices 按顺序列出顶点,而 tril_indices 按相反顺序列出顶点。它们通常用于获取矩阵的上三角或下三角的索引。

关于python - 从 pandas 数据帧生成边缘列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42454690/

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