python - 我需要比较 2 个不同数据帧的 2 个字段(如果匹配),我们需要填充详细信息,否则在 python 中填充空值

标签 python string pandas merge comparison

我有 2 个 csv 文件 df1

x   y  z      m
a   b  c  [apple,iphone,watch,newdevice]
e   w  q   NaN
w   r  t  [pixel,google]
s   t  q  [india,computer]

df2

new      code    file
apple    appl    ofo
lg       weew    ofe
htc      rrr     ofr
google   ggle    ofg

现在我需要检查 df1 中的 m 值与 df2 中的新值是否匹配,我需要将新值的详细信息合并到 df1 中,否则我们需要填充空值 我需要使用 python 请帮助我

示例输出

x   y  z      m                                code     file
a   b  c  [apple,iphone,watch,newdevice]       aapl     ofo
e   w  q   NaN                                 null     null
w   r  t  [pixel,google,]                      ggle     ofg
s   t  q  [india,computer]                     null     null

最佳答案

这里是通过 np.isin 的基于 NumPy 的方法,它根据 1d 数组测试 2d 数组中的每个值。但实际上这应该被视为最后的手段:串联列表效率低下,并且您将面临大型数据集的性能问题。

注意,如果列表中存在多个匹配项,argmax 将仅检查第一个匹配项。

import pandas as pd, numpy as np

df1 = pd.DataFrame({'x': list('aws'), 'y': list('brt'), 'z': list('ctq'),
                    'm': [['apple', 'iphone', 'watch', 'newdevice'],
                          ['google', 'pixel'], ['india', 'computer']]})

split = pd.DataFrame(df1['m'].values.tolist()).values
mask = np.isin(split, df2['new'].values).argmax(1)
df1['new'] = split[np.arange(split.shape[0]), mask]

df = pd.merge(df1, df2, on='new', how='left').drop('new', 1)

print(df)

   x  y  z                                  m  code file
0  a  b  c  [apple, iphone, watch, newdevice]  appl  ofo
1  w  r  t                    [google, pixel]  ggle  ofg
2  s  t  q                  [india, computer]   NaN  NaN

关于python - 我需要比较 2 个不同数据帧的 2 个字段(如果匹配),我们需要填充详细信息,否则在 python 中填充空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52652336/

相关文章:

python - 如何在 Python 中为实例分配属性?

JavaScript 搜索字符串错误

java - 这个正则表达式在 Java 中是如何工作的?

python - 加快 Pandas 数据框中字符串的整数编码

python - Pandas 数据框中单元格中的条件更改值

python - 如何使用具有可变形状输入的 Keras Conv2D 层

python - PyQt5 QTableWidget : select column with right click, 并在上下文菜单中显示删除条目

python - pip install pycairo 在 osx : 'pkg-config' search path problems 上失败

regex - 字符串在数字单词模式上分割

python - 重新索引排序系列