我有一个这样的数据帧df1:

A   B
AA  [a,b,c,d]
BB  [a,f,g,c]
CC  [a,b,l,m]

另一个是df2,如:

C   D
XX  [a,b,c,n]
YY  [a,m,r,s]
UU  [e,h,I,j]

我想根据df2[‘D’]和df1[‘B’]项之间的最高元素匹配,找出df2的C列和df1的A列,如果没有,则映射为NULL.

结果df将如下所示:

C      D         A   common_items
XX  [a,b,c,n]   AA    [a,b,c]
YY  [a,m,r,s]   CC    [a,m]
UU  [e,h,I,j]   Null    Null

在花费大量时间研究了iterTools和np操作并使用pd.merge‘int’之后,我得到的最接近的结果是:

np.intersect1d(df2.D, df1.B)

keys = ['B', 'D']
intersection = df1.merge(df2[keys], on=keys)

关于不同数据帧的两列的公共元素的数目的任何解决方案,将源df1[‘A’]映射到目标df2[‘c’]. [a,b,c,d]等是字符串列表.

生效日期:

df1.to_dict('list'):
{'A': ['AA', 'BB', 'CC'],
 'B': [['a', 'b', 'c', 'd'], ['a', 'f', 'g', 'c'], ['a', 'b', 'l', 'm']]}


df2.to_dict('list'):
{'C': ['XX', 'YY', 'UU'],
 'D': [['a', 'b', 'c', 'n'], ['a', 'm', 'r', 's'], ['e', 'h', 'l', 'j']]}

任何关于spark 源/Pandas 的东西都会真的断断续续.

推荐答案

You can convert to set, compute the intersections with and get the best match:

b = df1['B'].apply(set).to_numpy()
d = df2['D'].apply(set).to_numpy()

# compute pairwise intersections
common = d[:,None] & b

# get largest intersection per row
vlen = np.vectorize(len)
idx = np.argmax(vlen(common), axis=1)

# assign intersections and original ID
df2['common_items'] = common[np.arange(len(d)), idx]
df2['A'] = np.where(df2['common_items'].str.len()>0,
                    df1['A'].to_numpy()[idx], None)

输出:

    C             D common_items     A
0  XX  [a, b, c, n]    {b, a, c}    AA
1  YY  [a, m, r, s]       {a, m}    CC
2  ZZ  [m, b, c, d]    {b, d, c}    AA
3  UU  [e, h, I, j]           {}  None

中间体:

# common
array([[{'b', 'a', 'c'}, {'a', 'c'}, {'b', 'a'}],
       [{'a'}, {'a'}, {'a', 'm'}],
       [{'b', 'd', 'c'}, {'c'}, {'b', 'm'}],
       [set(), set(), set()]], dtype=object)

# vlen(common)
array([[3, 2, 2],
       [1, 1, 2],
       [3, 1, 2],
       [0, 0, 0]])

# idx
array([0, 2, 0, 0])

Python相关问答推荐

Tokenizer Docker:无法为Tokenizer构建轮子,这是安装pyproject.toml项目所需的

我可以使用极点优化这个面向cpu的pandas代码吗?

"Discord机器人中缺少所需的位置参数ctx

优化在numpy数组中非零值周围创建缓冲区的函数的性能

将DF中的名称与另一DF拆分并匹配并返回匹配的公司

我在使用fill_between()将最大和最小带应用到我的图表中时遇到问题

运行总计基于多列pandas的分组和总和

如何在Windows上用Python提取名称中带有逗号的文件?

将数据框架与导入的Excel文件一起使用

为什么默认情况下所有Python类都是可调用的?

Pandas:将多级列名改为一级

我如何根据前一个连续数字改变一串数字?

给定高度约束的旋转角解析求解

根据列值添加时区

字符串合并语法在哪里记录

Django—cte给出:QuerySet对象没有属性with_cte''''

下三角形掩码与seaborn clustermap bug

当条件满足时停止ODE集成?

在Google Drive中获取特定文件夹内的FolderID和文件夹名称

使用__json__的 pyramid 在客户端返回意外格式