Проверьте, есть ли подобная строка в том же столбце - PullRequest
1 голос
/ 02 апреля 2020

У меня есть такой фрейм данных,

df
col1             col2
 A        'the value is zero'
 B        'this is a cat'
 C        'the value is one'
 D        'nothing is here'
 E        'the colour is blue'
 F        'this is dog'
 G        'empty sequence'
 H        'the colour is red'
 I        'the colour is green'         1

Теперь я хочу, чтобы строки аналогичного типа помечались как 1, а другие как ноль, поэтому итоговый фрейм данных должен выглядеть следующим образом:

col1             col2                 col1
 A        'the value is zero'           1
 B        'this is a cat'               1
 C        'the value is one'            1
 D        'nothing is here'             0
 E        'the colour is blue'          1
 F        'this is dog'                 1
 G        'empty sequence'              0
 H        'the colour is red'           1
 I        'the colour is green'         1 

0 и 1 можно получить с помощью функции SequenceMatcher (SequenceMatcher (None, s1, s2) .ratio ()) и с некоторым пороговым значением мы можем сделать его равным нулю или единице.

Но если я использую циклы for, чтобы найти сходство между собой, выполнение займет больше времени. Ищите pandas ярлыки / pythoni c способ сделать это эффективно.

1 Ответ

3 голосов
/ 02 апреля 2020

Мы можем использовать difflib и проверить, найдем ли мы более 1 подобной строки (исключая ее собственную), посмотрев на длину списка, возвращаемого difflib.get_close_matches:

import difflib

df['col1'] = [(len(difflib.get_close_matches(x, df['col2'], cutoff=0.7))>1)*1 
              for x in df['col2']]

print(df)

   col1                            col2
0     1             'the value is zero'
1     1                 'this is a cat'
2     1              'the value is one'
3     0               'nothing is here'
4     1            'the colour is blue'
5     1                   'this is dog'
6     0                'empty sequence'
7     1             'the colour is red'
8     1           'the colour is green'        

Матрица подобия, основанная на нечеткое сопоставление

Также может быть интересно получить матрицу сходства, устанавливающую все значения в поворотном столбце в 1 если строки похожи. Для этого мы могли бы действовать так же, как описано выше, но сохраняя весь список, разбивая его и поворачивая результирующий кадр данных с помощью pd.crosstab:

df['sim'] = [difflib.get_close_matches(x, df['col2'], cutoff=0.7)  for x in df['col2']]
sim_df = df.explode('sim')
pd.crosstab(sim_df.col2, sim_df.sim)

sim             empty sequence  nothing is here  the colour is blue... the value is zero  this is a cat  this is dog
col2
empty sequence      1                0                     0         ...        0                   0            0
nothing is here     0                1                     0         ...        0                   0            0
the colour is blue  0                0                     1         ...        0                   0            0
the colour is green 0                0                     1         ...        0                   0            0
the colour is red   0                0                     1         ...        0                   0            0
the value is one    0                0                     0         ...        1                   0            0
the value is zero   0                0                     0         ...        1                   0            0
this is a cat       0                0                     0         ...        0                   1            1
this is dog         0                0                     0         ...        0                   1            1 
...