python - 从包含数组的不同列之间的匹配元素创建新列

标签 python arrays pandas for-loop

我有一个数据框,其中列 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/

相关文章:

python - 在一定数量的变量之后更改列表输出

python - 为什么我的父类(super class)调用我的子类方法?

python - 从 python 中的 .dat 文件导入数组

arrays - Swift 3 - 二元运算符 '==' 不能应用于两个 'MyStruct' 操作数

python - 为什么我的 DataFrame.loc 返回错误的行?

python - 如何告诉 `complete` 回退到默认值?

python - 使用 matplotlib 绘制数组列表

arrays - 如何将数组的元素移动到数组的开头

Python 对 pandas 数据框中的单词进行单数化

python - Pandas :仅当特定列中的值以以下开头时才选择数据框行