[英]Compare two columns and return the row numbers in Python
我有兩列 A = [11, 24, 7, 7, 0, 4, 9, 20, 3, 5] 和 B = [5, 8, 9, 1, 11]。 但它們有不同的行號。 我想查找 A 是否與 B 具有相同的元素並返回 A 和 B 的行號。例如,
A 和 B 具有相同的值 5,9, 11,返回的矩陣為 C = [5, 9, 11]
A的返回行號應該是row_A = [9, 6, 0]
B的返回行號應該是row_B = [0, 2, 4]
我可以使用python中的任何函數嗎? 謝謝
這是numpy.intersect1d
。 使用return_indices
參數,除了值之外,您還可以獲得索引。 如果 A/B 是 numpy 數組、pandas 系列或列表,這將起作用。
請注意,如果您的對象是 pandas 對象,則返回的索引是數組索引。 因此,如果您的系列沒有從 0 開始的 RangeIndex,您可以按數組位置對它們的 Index 對象進行切片以獲取實際的系列索引標簽。
import numpy as np
vals, idxA, idxB = np.intersect1d(A, B, return_indices=True)
vals
#array([ 5, 9, 11])
idxA
#array([9, 6, 0])
idxB
#array([0, 2, 4])
如果您有兩個不同的數據幀,請為每個數據幀復制另一列中的索引並加入列:
df_A["index"] = df.index
df_B["index"] = df.index
df_A.merge(df_B, left_on="A", right_on="B", how="inner")
df = pd.DataFrame(data = {"A":[11, 24, 7, 7, 0, 4, 9, 20, 3, 5], "B" : [5, 8, 9, 1, 11, -1,-1,-1,-1,-1]})
df_A = df[["A"]]
df_A["index"] = df.index
df_B = df[["B"]]
df_B["index"] = df.index
df_A.merge(df_B, left_on="A", right_on="B", how="inner")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.