[英]Python - Pandas remove rows after self-join (merge)
類似於這個問題的種類: Pandas 合並刪除重復行
我正在使用 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 中執行此操作? 感謝您的幫助!
丑陋,但完成工作:
import pandas as pd
df = pd.DataFrame({
'type':['a','b','c','d','e'],
'value':[100,200,300,400,500]})
import itertools
combinations = pd.DataFrame(list(itertools.combinations(df['type'], 2)), columns=['type_x', 'type_y'])
combinations = pd.merge(combinations, df, left_on='type_x', right_on='type') \
.drop(columns=['type']) \
.rename(columns={'value': 'value_x'})
combinations = pd.merge(combinations, df, left_on='type_y', right_on='type') \
.drop(columns=['type']) \
.rename(columns={'value': 'value_y'})
combinations
類型_x | type_y | 值_x | value_y | |
---|---|---|---|---|
0 | 一個 | b | 100 | 200 |
1 | 一個 | c | 100 | 300 |
2 | b | c | 200 | 300 |
3 | 一個 | d | 100 | 400 |
4 | b | d | 200 | 400 |
5 | c | d | 300 | 400 |
6 | 一個 | e | 100 | 500 |
7 | b | e | 200 | 500 |
8 | c | e | 300 | 500 |
9 | d | e | 400 | 500 |
這里不需要 pandas.merge() 。 只需將 output 組合輸入到 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.