-
繁花不似锦
使用apply, 和' '.join, 然后使用列表推导来获取匹配的值此外,您必须使用axis=1它才能工作:print(df.apply(lambda x: ' '.join([i for i in x['Col1'].split() if i in x['Col2'].split()]), axis=1))输出:0 the cat1 2 chickendtype: object如果你想要NULL,而不仅仅是一个空值,请使用:print(df.apply(lambda x: ' '.join([i for i in x['Col1'].split() if i in x['Col2'].split()]), axis=1).str.replace('', 'NULL'))输出:0 the cat1 NULL2 chickendtype: object
-
慕娘9325324
这里不需要使用 lambda 函数,只需检查每个单词是否包含在同一列的字符串中。zip() 函数对于列迭代非常有用。这是一种方法:import pandas as pddata_frame = pd.DataFrame( {'col1':{ 1:'the cat crossed a road', 2:'the dog barked', 3:'the chicken barked',}, 'col2':{ 1: 'the cat alligator', 2: 'some words here', 3: 'chicken soup'}})# output the overlap as a listoutput = [ [word for word in line1.split() if word in line2.split()] for line1, line2 in zip(data_frame['col1'].values, data_frame['col2'].values)]# To add your new values a columndata_frame['col3'] = output# Or, if desired, keep as a list and remove empty rows output = [row for row in output if row]
-
慕哥9229398
检查l=[' '.join([t for t in x if t in y]) for x, y in zip(df1.Col1.str.split(' '),df2.Col2.str.split(' '))]pd.DataFrame({'Col3':l})Out[695]: Col30 the cat1 2 chicken