查找每两行 pandas data.frame 的字符串之间的差异

我是python新手,我为此苦苦挣扎了一段时间。我有一个看起来像这样的文件:


    name   seq

1   a1     bbb

2   a2     bbc

3   b1     fff

4   b2     fff

5   c1     aaa

6   c2     acg

其中 name 是字符串的名称,seq 是字符串。我想要一个新列或一个新数据框来指示每两行之间没有重叠的差异数量。例如,我想要名称 [a1-a2] 然后 [b1-b2] 和最后 [c1-c2] 之间的序列之间的差异数。


所以我需要这样的东西:


    name   seq   diff  

1   a1     bbb    NA   

2   a2     bbc    1

3   b1     fff    NA

4   b2     fff    0

5   c1     aaa    NA

6   c2     acg    2

非常感谢任何帮助


慕虎7371278
浏览 168回答 4
4回答

慕沐林林

看起来您想要字符串对的杰卡德距离。groupby这是使用and的一种方法scipy.spatial.distance.jaccard:from scipy.spatial.distance import jaccardg = df.groupby(df.name.str[0])df['diff'] = [sim for _, seqs in g.seq for sim in               [float('nan'), jaccard(*map(list,seqs))]]print(df)  name  seq  diff1   a1  bbb   NaN2   a2  bbc   1.03   b1  fff   NaN4   b2  fff   0.05   c1  aaa   NaN6   c2  acg   2.0

饮歌长啸

Levenshtein距离替代:import Levenshteins = df['name'].str[0]out = df.assign(Diff=s.drop_duplicates(keep='last').map(df.groupby(s)['seq']                    .apply(lambda x: Levenshtein.distance(x.iloc[0],x.iloc[-1]))))  name  seq  Diff1   a1  bbb   NaN2   a2  bbc   1.03   b1  fff   NaN4   b2  fff   0.05   c1  aaa   NaN6   c2  acg   2.0

鸿蒙传说

作为第一步,我使用以下方法重新创建了您的数据:#!/usr/bin/env python3import pandas as pd# Setupdata = {'name': {1: 'a1', 2: 'a2', 3: 'b1', 4: 'b2', 5: 'c1', 6: 'c2'}, 'seq': {1: 'bbb', 2: 'bbc', 3: 'fff', 4: 'fff', 5: 'aaa', 6: 'acg'}}df = pd.DataFrame(data)解决方案 您可以尝试迭代数据框并将seq最后一次迭代的值与当前迭代值进行比较。为了比较两个字符串(存储在数据框的seq列中),您可以应用一个简单的列表推导,如在此函数中:def diff_letters(a,b):    return sum ( a[i] != b[i] for i in range(len(a)) )迭代 Dataframe 行diff = ['NA']row_iterator = df.iterrows()_, last = next(row_iterator)# Iterate over the df get populate a list with result of the comparisonfor i, row in row_iterator:    if i % 2 == 0:        diff.append(diff_letters(last['seq'],row['seq']))    else:        # for odd row numbers append NA value        diff.append("NA")    last = rowdf['diff'] = diff结果看起来像这样  name  seq diff1   a1  bbb   NA2   a2  bbc    13   b1  fff   NA4   b2  fff    05   c1  aaa   NA6   c2  acg    2

侃侃尔雅

检查这个import pandas as pddata = {'name':&nbsp; ['a1', 'a2','b1','b2','c1','c2'],&nbsp; &nbsp; 'seq': ['bbb', 'bbc','fff','fff','aaa','acg']&nbsp; &nbsp; }df = pd.DataFrame (data, columns = ['name','seq'])diffCntr=0df['diff'] = np.nani=0while i < len(df)-1:&nbsp; &nbsp; diffCntr=np.nan&nbsp; &nbsp; item=df.at[i,'seq']&nbsp; &nbsp; df.at[i,'diff']=diffCntr&nbsp; &nbsp; diffCntr=0&nbsp; &nbsp; for j in df.at[i+1,'seq']:&nbsp; &nbsp; &nbsp; &nbsp; if item.find(j) < 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; diffCntr +=1&nbsp; &nbsp; df.at[i+1,'diff']=diffCntr&nbsp; &nbsp; i +=2&nbsp; &nbsp;&nbsp;df&nbsp;&nbsp;结果是这样的:&nbsp; &nbsp; name seq&nbsp; &nbsp; diff0&nbsp; &nbsp;a1&nbsp; &nbsp;bbb&nbsp; &nbsp; NaN1&nbsp; &nbsp;a2&nbsp; &nbsp;bbc&nbsp; &nbsp; 1.02&nbsp; &nbsp;b1&nbsp; &nbsp;fff&nbsp; &nbsp; NaN3&nbsp; &nbsp;b2&nbsp; &nbsp;fff&nbsp; &nbsp; 0.04&nbsp; &nbsp;c1&nbsp; &nbsp;aaa&nbsp; &nbsp; NaN5&nbsp; &nbsp;c2&nbsp; &nbsp;acg&nbsp; &nbsp; 2.0
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python