Column contains column 1

2019-07-22 12:05发布

问题:

I have a dataframe. I can test whether, (C), on each row, the number in column (B) is in the string column (A).

df = pd.DataFrame({'A': ["me 1 23", "me", "123", "me 12", "12 me"],
                   'B': [123,        123,  123,      12,   12    ]})

df = df.dropna()
df['C']=df.A.str.contains(r'\b(?:{})\b'.format('|'.join(df.B.astype(str)))).astype(int)
print(df)

This gives the correct answer:

         A    B  C
0  me 1 23  123  0
1       me  123  0
2      123  123  1
3    me 12   12  1
4    12 me   12  1

But when I change the number (B) on row 1 I get the incorrect answer (C) on row 0:

         A    B  C
0  me 1 23  123  1
1       me   23  0
2      123  123  1
3    me 12   12  1
4    12 me   12  1

回答1:

I feel like that is row-wise check

[str(y) in x for x , y in zip(df.A,df.B)]
Out[1308]: [False, False, True, True, True]