Column contains column 1

社会主义新天地 提交于 2020-01-15 09:13:22

问题


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]


来源:https://stackoverflow.com/questions/55972214/column-contains-column-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!