使用熊猫识别列之间的相似值

时间:2020-04-29 18:57:26

标签: python python-3.x pandas

我有两列

def get_absolute_url(self): # new
    return reverse('lawyer_detail', args=[str(self.id)])

我想检查两列之间是否有相似的值,而不管它们的行如何,并将其放置在新列中(类似)

这是我想要的输出

A         B         
2001     2003
2003     1999
1990     2001
1995     2010
2004     1996

谢谢

4 个答案:

答案 0 :(得分:1)

IIUC,您可以使用isin

df[df['A'].isin(df['B'])]['A'].values

答案 1 :(得分:1)

如果用“相似”来表示相等,则可以使用isin方法来解决。我还假设新列中的值顺序无关紧要。

>>> df['SIMILAR'] = df.loc[df['A'].isin(df['B']), 'A']
>>> df
      A     B  SIMILAR
0  2001  2003   2001.0
1  2003  1999   2003.0
2  1990  2001      NaN
3  1995  2010      NaN
4  2004  1996      NaN

答案 2 :(得分:0)

要查找重复的值,您可以执行以下操作:

duplicateRowsDF = pdData[pdData.duplicated()]
print("Duplicate Rows except first occurrence based on all columns are :")
print(duplicateRowsDF)

响应应该是这样的:

SIMILAR
2003
2001

然后,您仅使用这些新数据创建一个新的列

pdData["Similar"] = duplicateRowsDF

答案 3 :(得分:0)

设置交集的代码高尔夫(假设标准范围索引):

df['C'] = pd.Series([*{*df.A} & {*df.B}])

      A     B       C
0  2001  2003  2001.0
1  2003  1999  2003.0
2  1990  2001     NaN
3  1995  2010     NaN
4  2004  1996     NaN