简体   繁体   English

比较两列并在 Python 中返回行号

[英]Compare two columns and return the row numbers in Python

I have two columns A = [11, 24, 7, 7, 0, 4, 9, 20, 3, 5] and B = [5, 8, 9, 1, 11].我有两列 A = [11, 24, 7, 7, 0, 4, 9, 20, 3, 5] 和 B = [5, 8, 9, 1, 11]。 But they have different row numbers.但它们有不同的行号。 I want to find if A has the same element as B does and return the row numbers of A and B. For example,我想查找 A 是否与 B 具有相同的元素并返回 A 和 B 的行号。例如,

A and B have the same value 5,9, 11 and the returned matrix is C = [5, 9, 11] A 和 B 具有相同的值 5,9, 11,返回的矩阵为 C = [5, 9, 11]

The returned row number of A should be row_A = [9, 6, 0] A的返回行号应该是row_A = [9, 6, 0]

The returned row number of B should be row_B = [0, 2, 4] B的返回行号应该是row_B = [0, 2, 4]

Are there any function in python I can use?我可以使用python中的任何函数吗? Thanks谢谢

This is numpy.intersect1d .这是numpy.intersect1d Using the return_indices argument you can also get the indices in addition to the values.使用return_indices参数,除了值之外,您还可以获得索引。 This will work if A/B are numpy arrays, pandas Series, or lists.如果 A/B 是 numpy 数组、pandas 系列或列表,这将起作用。

Note, if your objects are pandas objects, the returned indices are the array indices.请注意,如果您的对象是 pandas 对象,则返回的索引是数组索引。 So if your Series don't have a RangeIndex starting from 0, you can slice their Index objects by the array locations to get the actual Series Index labels.因此,如果您的系列没有从 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])

If you have two different dataframes, copy index in another column for each and join on columns:如果您有两个不同的数据帧,请为每个数据帧复制另一列中的索引并加入列:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM