类似于这个问题:Pandas merge removing duplicate rows
我正在使用 Python pandas -
输入:
df = pd.DataFrame({
'type':['a','b','c','d','e'],
'value':[100,200,300,400,500]})
我想自行加入此列表:
df_merge = pd.merge(df, df,on=['type'])
但我只想保留下面的行:
type_x value_x type_y value_y
a 100 b 200
a 100 c 300
a 100 d 400
a 100 e 500
b 200 c 300
b 200 d 400
b 200 e 500
c 300 d 400
c 300 e 500
d 400 e 500
我怎样才能在 Pandas 中做到这一点?谢谢您的帮助!
最佳答案
这里不需要 pandas.merge() 。只需将组合输出输入 DataFrame 构造函数(使用一点技巧即可将两个 2 元组转换为包含 4 个元素的列表):
from itertools import combinations
import pandas
types = ['a','b','c','d','e']
values = [100,200,300,400,500]
rows = [[*pair1, *pair2]
for pair1, pair2 in combinations(zip(types, values), 2)]
columns = [f"{col}_{var}"
for col in ['type', 'value']
for var in ['x', 'y']]
pandas.DataFrame(rows, columns=columns)
关于Python - Pandas 在自连接(合并)后删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66230118/