我有一个数据框,其中列 col2 的行包含数字列表
col1 col2
1 . 54319 54319, 54317
2 . 54317 37604, 37603, 37605
3 . 37603 123
4 . 37604 124
5 . 37605 1255
我想找到 col1 和 col2 之间的匹配项,并创建一个新列“new”,附加 col2 中包含与 col1 匹配的组
结果
col1 col2 new
1 . 54319 54319, 54317 54319, 54317
2 . 54317 37604, 37603, 37605 54319, 54317
3 . 37603 123 37604, 37603, 37605
4 . 37604 124 37604, 37603, 37605
5 . 37605 1255 37604, 37603, 37605
这是我的代码,但它崩溃了。我想我无法读取 col2[rows] 行中包含的列表
new = []
for val in col1:
for i in col2:
if val in i:
new.append(i)
else:
continue
打印(新)
最佳答案
如果匹配col2
中的col1
值,则想法是ltest,并且对于一般解决方案返回默认值,这里不匹配
如果值不存在:
f = lambda x: next(iter([y for y in df['col2'].tolist() if str(x) in y]), 'no match')
df['new'] = df['col1'].apply(f)
print (df)
col1 col2 new
1 123 123, 562, 7779 123, 562, 7779
2 456 456, 111, 123 456, 111, 123
3 789 667, 1213, 456 1011, 444, 909, 789
4 1011 1213, 445, 909, 123 1011, 444, 909, 789
5 1213 1011, 444, 909, 789 667, 1213, 456
对于值列表也同样有效:
df['new'] = df['col1'].apply(f)
print (df)
col1 col2 new
1 123 [123, 562, 7779] [123, 562, 7779]
2 456 [456, 111, 123] [456, 111, 123]
3 789 [667, 1213, 456] [1011, 444, 909, 789]
4 1011 [1213, 445, 909, 123] [1011, 444, 909, 789]
5 1213 [1011, 444, 909, 789] [667, 1213, 456]
编辑:
使用 split
和 ,
的最后一个解决方案:
df['col2'] = df['col2'].str.split(', ')
f = lambda x: next(iter([y for y in df['col2'].tolist() if str(x) in y]), 'no match')
df['new'] = df['col1'].apply(f)
print (df)
col1 col2 new
1 54319 [54319, 54317] [54319, 54317]
2 54317 [37604, 37603, 37605] [54319, 54317]
3 37603 [123] [37604, 37603, 37605]
4 37604 [124] [37604, 37603, 37605]
5 37605 [1255] [37604, 37603, 37605]
关于python - 从包含数组的不同列之间的匹配元素创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58748304/