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

2024-09-27 09:33:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有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

现在我需要用df2中的新值检查df1中的m值,如果它匹配,我需要将新值的细节合并到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

Tags: applegooglecodenannullcomputerfilewatch
1条回答
网友
1楼 · 发布于 2024-09-27 09:33:37

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

注意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

相关问题 更多 >

    热门问题