找出两列值之间的不匹配

2024-09-29 21:50:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧df1看起来像-

user     data                               dep                    
1        ['dep_78','fg7uy8']                78
2        ['the_dep_45','34_dep','re23u']    45
3        ['fhj56','dep_89','hgjl09']        91

如果“dep”列中的值与“dep”列中的值相匹配,请查看“dep”列中的值。例如,用户1的数据列中的dep_78与dep列中的dep 78匹配。我想输出不匹配的行。所以结果应该会告诉我-

^{pr2}$

问题是只取带有字符串“dep”的数据列中的特定值,然后将这些字符串所附的数字与“dep”列进行比较。在


Tags: the数据字符串用户data数字df1user
2条回答

你能做到的

def select(row):
    keystring = 'dep_'+str(row['dep'])
    result = []
    for one in row['data']:
        if (one!=keystring)&('dep' in one):
            result.append(one)
    return result

df['data'] =df.apply(lambda x:select(x),axis=1)
df['datalength'] = df['data'].map(lambda x:len(x))
result = df[df['datalength']>0][df.columns[:3]]
print(result)
   user                  data  dep
1     2  [the_dep_45, 34_dep]   45
2     3              [dep_89]   91

这个怎么样?在

import re

r = re.compile('\d+')

idx = df.apply(lambda x: str(x['dep']) in r.search(x['data']).group(0), axis=1)

0     True
1     True
2    False
dtype: bool


df[idx]

   user                             data  dep
0     1              ['dep_78','fg7uy8']   78
1     2  ['the_dep_45','34_dep','re23u']   45

相关问题 更多 >

    热门问题