我有一份数据。我想测试(C),在每一行中,(B)栏中的数字是否在字符串(A)中。
df = pd.DataFrame({'A': ["me 123", "me-123", "1234", "me 12", "123 and"],
'B': [123, 123, 123, 123, 6]})我想得到:
A B C
0 me 123 123 1
1 me-123 123 1
2 1234 123 0
3 me 12 123 0
4 123 and 6 0各种方法几乎可以管理这一点(1):
df['C'] = [str(y) in x for x , y in zip(df.A.str.split(' '),df.B)]
A B C
0 me 123 123 True
1 me-123 123 False
2 1234 123 False
3 me 12 123 False
4 123 and 6 False或(2):
df['C'] = [str(y) in x for x , y in zip(df.A,df.B)]
A B C
0 me 123 123 True
1 me-123 123 True
2 1234 123 True
3 me 12 123 False
4 123 and 6 False或(3):
df['C']=df.A.str.contains(r'\b(?:{})\b'.format('|'.join(df.B.astype(str)))).astype(int)
A B C
0 me 123 123 1
1 me-123 123 1
2 1234 123 0
3 me 12 123 0
4 123 and 6 1或(4):
def fun (A,B):
return str(B) in str(A)
f = np.vectorize(fun, otypes=[int])
df["C"] = f(df['A'], df['B'])
A B C
0 me 123 123 1
1 me-123 123 1
2 1234 123 1
3 me 12 123 0
4 123 and 6 0或(5):
df['A1'] = df['A'] .apply(word_tokenize)不认识-作为一个空间。我怎么才能在上面得到结果呢?
发布于 2019-05-20 15:40:27
一种基于extract的矢量化方法
df.A.str.extract('(\d+)', expand=False).astype(int).eq(df.B,0).astype(int)
Out[347]:
0
0 1
1 1
2 0
3 0
4 0发布于 2019-05-20 15:39:04
re.findall
pat = re.compile('\d+')
df.assign(C=[1 if str(b) in re.findall(pat, a) else 0 for a, b in zip(df.A, df.B)])
A B C
0 me 123 123 1
1 me-123 123 1
2 1234 123 0
3 me 12 123 0
4 123 and 6 0pandas.Series.str.findall
非常相似
df.assign(C=df.A.str.findall(pat).str[0].eq(df.B.astype(str)).astype(int))https://stackoverflow.com/questions/56224014
复制相似问题