给出一个数据框
d = {'col1': [['how', 'are', 'you'], ['im', 'fine', 'thanks'], ['you', 'know'], [np.nan]],
'col2': [['tell', 'how', 'me', 'you'], ['who', 'cares'], ['know', 'this', 'padewan'], ['who', 'are', 'you']]
df = pd.DataFrame(data=d)
我要创建第三列col3
,它是col2
列表中包含在col1
列表中相应行的列表中的任何元素,否则{ {1}}。
必须采用任何匹配的元素。
在这种情况下,np.nan
将是:
col3
我尝试过
col1 col2 col3
0 ['how', 'are', 'you'] ['tell', 'how, 'me', 'you'] ['how', 'you']
1 ['im', 'fine', 'thanks'] ['who', 'cares'] [np.nan]
2 ['you', 'know'] ['know', 'this', 'padewan'] ['know']
3 [np.nan] ['who', 'are', 'you'] [np.nan]
这根本不起作用,所以任何想法都将非常有帮助。
答案 0 :(得分:4)
类似这样的东西:
df['col3'] = [list(set(a).intersection(b)) for a, b in zip(df.col1, df.col2)]
输出:
col1 col2 col3
0 [how, are, you] [tell, how, me, you] [you, how]
1 [im, fine, thanks] [who, cares] []
2 [you, know] [know, this, padewan] [know]
3 [nan] [who, are, you] []
答案 1 :(得分:3)
另一个版本:
function extract(){
var textsTol=GM_getValue("textsTol",[]);
var texts = [];
var list = document.querySelectorAll("div[class='r']")
for (var i=0;i<list.length;i++){
texts.push(list[i].textContent)
}
console.log(texts);
}
打印:
df['col3'] = df.apply(lambda x: [*set(x['col1']).intersection(x['col2'])] or [np.nan], axis=1 )
print(df)
答案 2 :(得分:2)
我将在np.intersect1d
的帮助下编写一个单独的函数并应用:
def intersect_nan(a,b):
ret = np.intersect1d(a,b)
return list(ret) if len(ret)>0 else [np.nan]
df['col3'] = [intersect_nan(a,b) for a,b in zip(df['col1'], df['col2'])]
输出:
col1 col2 col3
0 [how, are, you] [tell, how, me, you] [how, you]
1 [im, fine, thanks] [who, cares] [nan]
2 [you, know] [know, this, padewan] [know]
3 [nan] [who, are, you] [nan]
答案 3 :(得分:1)
类似这样的东西:
d = {'col1': [['how', 'are', 'you'], ['im', 'fine', 'thanks'], ['you', 'know'], [numpy.nan]],
'col2': [['tell', 'how', 'me', 'you'], ['who', 'cares'], ['know', 'this', 'padewan'],
['who', 'are', 'you']]}
df = pandas.DataFrame(d)
list_col3 = []
for index, row in df.iterrows():
a_set= set(row['col1'])
b_set= set(row['col2'])
if len(a_set.intersection(b_set)) > 0:
list_col3.append(list(a_set.intersection(b_set)))
else:
list_col3.append([numpy.nan])
df['col3'] = list_col3
print(df)
输出:
col1 col2 col3
0 [how, are, you] [tell, how, me, you] [how, you]
1 [im, fine, thanks] [who, cares] [nan]
2 [you, know] [know, this, padewan] [know]
3 [nan] [who, are, you] [nan]