【问题标题】:Find and match a string in 2 dataframes python pandas在 2 个数据帧 python pandas 中查找并匹配一个字符串
【发布时间】:2021-05-31 07:30:52
【问题描述】:

我有两个数据框(df1、df2),我想在df1 中创建一个新列,在df2 中找到"Slave" 和"Name" 在df1 中并插入@987654328 df1 中同一行中该行的@。

>>> df2

SN  Slave                  Add  FullName    
0   21010730236TJ5900031    1   1.1.1   
1   21010730236TJ5902800    2   1.1.2   
2   21010730236TJ5902787    3   1.1.3   
3   21010730236TJ5902784    4   1.1.4   
>>> df1

SN        num   Name                        
0         #INV1 ESN:21010730236TJ5902772
1         #INV3 ESN:21010730236TJ5902787
2         #INV5 ESN:21010730236TJ5902785
3         #INV2 ESN:21010730236TJ5902800
4         #INV4 ESN:21010730236TJ5902784

谢谢

【问题讨论】:

  • Mahmoud KhoshGoftar,见下文...这是您想要的吗?

标签: python pandas dataframe compare


【解决方案1】:
import pandas as pd
data1 =[[0,         "#INV1", "ESN:21010730236TJ5902772"],
[1,        "#INV3", "ESN:21010730236TJ5902787"],
[2,        "#INV5", "ESN:21010730236TJ5902785"],
[3,         "#INV2", "ESN:21010730236TJ5902800"],
[4,         "#INV4", "ESN:21010730236TJ5902784"]]

data2=[[0,   "21010730236TJ5900031",    1,   "1.1.1"],   
[1,   "21010730236TJ5902800",    2,   "1.1.2"],   
[2,   "21010730236TJ5902787",    3,   "1.1.3"],   
[3,   "21010730236TJ5902784",    4,   "1.1.4"]]

df1 = pd.DataFrame(data1, columns=["SN","num","Name"])
df2 = pd.DataFrame(data2, columns=["SN","Slave","Add","FullName"])

您可以执行以下操作:

#remove the ESN: from df1
df1["Name"]=df1["Name"].str.replace("ESN:","") 

#make a new DataFrame merging the df1 and df2
result =pd.merge(left=df1, right=df2, how='left', left_on='Name', right_on='Slave')

#drop the columns of the df2 from the result DataFrame
result.drop(['SN_y', 'Add',"Slave"], axis=1, inplace=True)

#rename the columns of the result DataFrame to match the df1
result.columns=["SN","num","Name","FullName"]

#adding the ESN: again
result["Name"]="ESN:"+result["Name"]

这就是result DataFrame 的样子(检查你想要的索引):

    SN  num     Name                        FullName
0   0   #INV1   ESN:21010730236TJ5902772    NaN
1   1   #INV3   ESN:21010730236TJ5902787    1.1.3
2   2   #INV5   ESN:21010730236TJ5902785    NaN
3   3   #INV2   ESN:21010730236TJ5902800    1.1.2
4   4   #INV4   ESN:21010730236TJ5902784    1.1.4

【讨论】:

    猜你喜欢
    • 2019-03-16
    • 2020-10-14
    • 2020-04-11
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 2021-08-12
    相关资源
    最近更新 更多