我有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
答案 0 :(得分:1)
这是通过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