使用pandas-python映射两个数据帧

使用pandas-python映射两个数据帧,python,pandas,dataframe,Python,Pandas,Dataframe,有两个数据帧 import pandas as pd 输入 df1 df2 映射具有相似列的两个数据帧 从df2获取至少计数为2的匹配列。这里的单元格和标记与带有2个值的df1匹配 预期输出: name cell marks passwd 0 tomm 2 11111 2548 1 tonmmm 2 11111 2549 你可以试试这个: df1 = pd.DataFrame([['tom', 2, 11111]]

有两个数据帧

import pandas as pd
输入

df1

df2

映射具有相似列的两个数据帧

从df2获取至少计数为2的匹配列。这里的
单元格
标记
与带有2个值的df1匹配

预期输出:

    name    cell    marks   passwd
0   tomm    2      11111     2548
1   tonmmm  2      11111     2549

你可以试试这个:

df1 = pd.DataFrame([['tom', 2, 11111]], columns=["name", "cell", "marks"])

df2 = pd.DataFrame([['tomm', 2, 11111, 2548],
                    ['matt', 2, 158416, 2483],
                    ['tonmmm', 2, 11111, 2549]
                    ], columns=["name", "cell", "marks", "passwd"])

temp=[len([i for i in list(row)[1:] if i in list(df1.iloc[0,:])])>=2 for row in df2[df2.columns[:len(df2.columns)-1]].to_records()]
newdf=df2[temp]
print(newdf)
输出:

     name  cell  marks  passwd
0    tomm     2  11111    2548
2  tonmmm     2  11111    2549
   name  cell  marks  passwd
0   tom     2  11111    2549
1  tomm     2  11111    2548
编辑:如果要根据匹配数对其进行排序,可以尝试:

import pandas as pd
import numpy as np
df1 = pd.DataFrame([['tom', 2, 11111]], columns=["name", "cell", "marks"])  
df2 = pd.DataFrame([['tomm', 2, 11111, 2548],['matt', 2, 158416, 2483], ['tom', 2, 11111, 2549]], columns=["name", "cell", "marks", "passwd"])
temp=[len([i for i in list(row)[1:] if i in list(df1.iloc[0,:])]) for row in df2[df2.columns[:len(df2.columns)-1]].to_records()]
newdf=df2.copy().assign(val=temp).sort_values(by='val',ascending=False)
mask=np.where(newdf.val.ge(2), True, False)
newdf=newdf.drop(['val'],axis=1).reset_index(drop=True)[mask]
print(newdf)
输出:

     name  cell  marks  passwd
0    tomm     2  11111    2548
2  tonmmm     2  11111    2549
   name  cell  marks  passwd
0   tom     2  11111    2549
1  tomm     2  11111    2548

您如何定义相似?您是否在寻找标记相等的情况?@Hugolmn从df2获取列,该列的匹配计数至少为2。这里的
单元格
标记
与带有2的df1匹配values@NYCCoder从df2获取至少计数为2的匹配列。这里的
cell
marks
与具有2个值的df1匹配。我尝试使用此
df1=pd.DataFrame([[tom',211111]],columns=[“name”,“cell”,“marks”])df2=pd.DataFrame([[tomm',211112548],'matt',2,1584162483],'tom',2,11111,2549]],columns=[“name”、“cell”、“marks”、“passwd”])
一个案例中有三个值匹配。它应该作为第一个值返回。如何修改它以按值的降序获得它我刚刚编辑了该案例的答案@somara4935。希望它对您有用!如果您觉得有用,请:)!
   name  cell  marks  passwd
0   tom     2  11111    2549
1  tomm     2  11111    2548