想想我有一个数据帧两列:
第1列:
第1行:堆栈溢出
第2行:Python的
第2列:
行1:[ '栈', '堆栈溢出']
行2:[ 'Python编程', '蛇蟒']
我想要做精确匹配按行(可选),并返回相应的标志。
输出:
[0]匹配
[1]不匹配
尝试:我已经“在”在一个循环功能试过了,但也给部分匹配的“匹配”。
码:
for (item, Value),(item1, Value1) in zip(df1['Column1'].iteritems(),df2['Column2'].iteritems()):
if str(Value).strip() in str(Value1).strip():
found.append(1)
我想你需要:
def isMatch(row):
for i in row['b']:
if i == row['a']:
return 'Match'
return 'Not Match'
df['c'] = df.apply(lambda x: isMatch(x), axis=1)
print(df)
好吧,我会尽量回答这个问题,所以如果其他人也有类似的问题。基本上,你正在寻找检查col1
值在col2
(列表)。你可以很容易地使用isin
。应用numpy的where
功能,您可以创建一个标志。
这里是一个样机。
df = pd.DataFrame({
'col1': ['Stack Overflow', 'Python'],
'col2': [ ['Stack', 'Stack Overflow'], ['Python Programming', 'Python Snake']]})
df['Flag'] =df.apply(lambda x: x['col1'] in x['col2'], axis=1)
df
下面的结果:
col1 col2 Flag
0 Stack Overflow [Stack, Stack Overflow] True
1 Python [Python Programming, Python Snake] False
让我知道,如果它的工作原理。