[英]Pandas: How to get Unique combinations of two column values in either ways?
[英]How to get all unique combinations of values in one column that are in another column
從 dataframe 開始,如下所示:
df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': ['a', 'b', 'b', 'b', 'a']})
A B
0 1 a
1 2 b
2 3 b
3 4 b
4 5 a
像這樣獲得 dataframe 的最佳方法是什么?
pd.DataFrame({'source': [1, 2, 2, 3], 'target': [5, 3, 4, 4]})
source target
0 1 5
1 2 3
2 2 4
3 3 4
對於每次 A 列中的一行在 B 列中與 A 列中的另一行具有相同的值時,我想將該關系的唯一實例保存在新的 dataframe 中。
這非常接近:
df.groupby('B')['A'].unique()
B
a [1, 5]
b [2, 3, 4]
Name: A, dtype: object
但我現在最好把它轉換成一個 dataframe,我的大腦已經癱瘓了。
在您的情況下,您可以執行itertools.combinations
import itertools
s = df.groupby('B')['A'].apply(lambda x : set(list(itertools.combinations(x, 2)))).explode().tolist()
out = pd.DataFrame(s,columns=['source','target'])
out
Out[312]:
source target
0 1 5
1 3 4
2 2 3
3 2 4
使用合並 function
df.merge(df, how = "outer", on = ["B"]).query("A_x < A_y")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.