Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取数据框中的类似行,每个列仅更改1个或更多值_Python_Python 3.x_Pandas - Fatal编程技术网

Python 获取数据框中的类似行,每个列仅更改1个或更多值

Python 获取数据框中的类似行,每个列仅更改1个或更多值,python,python-3.x,pandas,Python,Python 3.x,Pandas,我的问题如下:假设您的数据帧NxM中填充了二进制数: pd.DataFrame([[0, 0, 0, 1, 0, 1], [0, 1, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 1, 0]] 我想得到两个相似行的索引或行(按行迭

我的问题如下:假设您的数据帧NxM中填充了二进制数:

pd.DataFrame([[0, 0, 0, 1, 0, 1],
              [0, 1, 0, 1, 0, 1],
              [1, 0, 0, 0, 0, 0],
              [1, 1, 0, 0, 0, 0],
              [0, 0, 0, 0, 1, 0],
              [1, 1, 0, 0, 1, 0]]
我想得到两个相似行的索引或行(按行迭代),每列只改变1个值或更多。例如,第一行的相似性为:

  • 如果每列仅更改一个值:
第0行:
[0,0,0,1,0,1]
->预期输出
[0,1,0,1,0,1]

第2行:
[1,0,0,0,0]
->预期输出
[1,1,0,0,0]

  • 如果每列更改两个值:
第2行:
[1,0,0,0,0,0]
->预期输出
[1,1,0,0,1,0]


第4行:
[0,0,0,0,1,0]
->预期输出
[1,1,0,0,1,0]
您可以移动记录。移位后,可以比较值以返回真/假。然后计算真实值。我为示例设置了true==1,因此在行之间正好有1个变化

我不确定你的具体结果应该是什么样的,但也许你可以加强这一点

print(df)

print(df.shift(-1))

df[df[df == df.shift(-1)].isna().sum(axis=1) == 1]
   0  1  2  3  4  5
0  0  0  0  1  0  1
1  0  1  0  1  0  1
2  1  0  0  0  0  0
3  1  1  0  0  0  0
4  0  0  0  0  1  0
5  1  1  0  0  1  0

     0    1    2    3    4    5
0  0.0  1.0  0.0  1.0  0.0  1.0
1  1.0  0.0  0.0  0.0  0.0  0.0
2  1.0  1.0  0.0  0.0  0.0  0.0
3  0.0  0.0  0.0  0.0  1.0  0.0
4  1.0  1.0  0.0  0.0  1.0  0.0
5  NaN  NaN  NaN  NaN  NaN  NaN

Out[54]: 
   0  1  2  3  4  5
0  0  0  0  1  0  1
2  1  0  0  0  0  0

一种可能性是使用汉明距离来获得行之间的成对距离:

import sklearn.metrics
comparisons = sklearn.metrics.pairwise_distances(df.values,metric='hamming')
nb_of_differences = (comparisons * df.shape[1]).astype(int)

汉明距离统计两个向量不同的位置数。最后,你会得到一个矩阵,给出第i行和第j行之间的差异数。

一个观察值。如果您的行是用数字表示的,而不是拆分成二进制,那么您可以通过异或生成距离一位的所有数字,每个数字都是
1、2、4、8、16、32、64、128
(假设您有8位)。相反,如果结果在集合
1、2、4、8、16、32、64、128
中,则与原始数字异或的任何数字都将相距一位。对于两位,它变得更复杂。您的数字列表将是
set(map(sum,itertools.compositions([1,2,4,8,16,32,64,128],r=2))
。(8位的长度为28,32位的长度为496个2位以外的数字)。例如
5^7
2
,它位于
1,2,4,8,16,32,64,128
集合中,因此距离为1位,但
5^9
12
集合中,因此距离为1位。另外,
5^2
还将返还您原来的
7
。而
5^128
给出的
133
也是一位距离。