Python 熊猫:如果列表包含来自另一个列表(x)的元素,则将匹配的x元素添加到新列中

Python 熊猫:如果列表包含来自另一个列表(x)的元素,则将匹配的x元素添加到新列中,python,pandas,Python,Pandas,我有一个像这样的数据框 col1 col2 col3 1 ab ['p','q','r','s'] 2 rx ['t','u','v','w'] 3 pq ['h','a','g','s'] 另一个列表x=[g,t,r,c] 我想创建一个新的col4列,其中的元素与col3中的列表x相匹配 执行代码后,数据帧将如下所示: col1 col2 col3

我有一个像这样的数据框

col1    col2     col3     
1       ab       ['p','q','r','s']
2       rx       ['t','u','v','w']
3       pq       ['h','a','g','s']
另一个列表x=[g,t,r,c]

我想创建一个新的col4列,其中的元素与col3中的列表x相匹配

执行代码后,数据帧将如下所示:

col1    col2     col3                  col4
1       ab       ['p','q','r','s']      r
2       rx       ['t','u','v','w']      t    
3       pq       ['h','a','g','s']      g
以下是我尝试过的:

x=['g','t','r','c']
for i in df['col3']:
    if (any(elem in i for elem in x)):
        df['col4']=x

我得到的错误值错误:值的长度与索引的长度不匹配

通过使用列表理解,这一行应该足够了:

df['col4'] = [ list(set(x) & set(df['col3'][i]) for i in range(len(df['col3']))]
你可以像这样使用apply方法

df['col4'] = df['col3'].apply(lambda y : [k for k in y if k in x])
如果有多个匹配项,也会处理这些匹配项

[k代表k in y,如果k in x]是一种列表理解方法,它提供了x和y中常见的元素列表,这里的y是col3的各个元素。如果你确定只有一个匹配,那么你可以这样做

df['col4'] = df['col3'].apply(lambda y : [k for k in y if k in x][0])
你可以试试

s=df.col3.str.join(',').str.get_dummies(',').reindex(columns=x,fill_value=0)
df['new']=s.dot(s.columns)
df
Out[290]: 
   col1 col2          col3 new
0     1   ab  [p, q, r, s]   r
1     2   rx  [t, u, v, w]   t
2     3   pq  [h, a, g, s]   g

您可以在一行中这样做:

df["col4"] = df["col3"].apply(lambda v: list(set(v).intersection(x)))
下面是一个完整的工作示例:

import pandas as pd


df = pd.DataFrame({"col1": [1, 2, 3],
                    "col2": ["ab", "rx", "pq"],
                    "col3": [['p','q','r','s'], ['t','u','v','w'], ['h','a','g','s']]})
x = {'g','t','r','c'}

df["col4"] = df["col3"].apply(lambda v: list(set(v).intersection(x)))
print(df)
#   col1 col2          col3 col4
#0     1   ab  [p, q, r, s]  [r]
#1     2   rx  [t, u, v, w]  [t]
#2     3   pq  [h, a, g, s]  [g]

我们可以迭代第3列和第x列的笛卡尔坐标以得到结果。此外,更快:

from itertools import product, chain

output = list(chain.from_iterable(set(first).intersection(last) 
                    for first, last in product(df.col3, [x]))
                    )

output 

['r', 't', 'g']


df['output'] = output


  col1  col2    col3    output
0   1   ab  [p, q, r, s]    r
1   2   rx  [t, u, v, w]    t
2   3   pq  [h, a, g, s]    g

col2是否与问题相关?col3是否也包含列表或字符串?col3是否包含列表?怎样或者它只是一个带字母的字符串?@ePi272314 col3包含一个字符串字符列表。我得到了ValueError:值的长度与indexi的长度不匹配。我刚刚编辑了代码。我只是再次运行它来确认输出。你的产出是多少?或者,您的数据是否超过三行,如上所述?