Skip to main content
 首页 » 编程设计

python之如何比较明喻列值上的两个不同数据框并将值放入其他数据框

2024年12月31日7arxive

我需要自动执行对文本文件的验证。我有两个文本文件,我需要检查一个文件中具有两列唯一组合的行是否存在于具有相同列组合的其他文本文件中,然后文本文件二中的新列需要写入文本文件一。

文本文件 1 有几千条记录,文本文件 2 被认为是对文本文件 1 的引用。

到目前为止,我已经编写了以下代码。请帮我解决这个问题。

import pandas as pd 
 
data=pd.read_csv("C:\\Users\\hp\\Desktop\\py\\sample2.txt",delimiter=',') 
df=pd.DataFrame(data) 
print(df) 
 
# uniquecal=df[['vehicle_Brought_City','Vehicle_Brand']] 
# print(uniquecal) 
 
data1=pd.read_csv("C:\\Users\\hp\\Desktop\\py\\sample1.txt",delimiter=',') 
df1=pd.DataFrame(data1) 
print(df1) 
 
# uniquecal1=df1[['vehicle_Brought_City','Vehicle_Brand']] 
# print(uniquecal1 

如何将车辆价格放入数据框 1 并将其保存到文本文件 1?

下面是我的示例数据集:

文件1:

   fname lname vehicle_Brought_City Vehicle_Brand  Vehicle_price 
0   aaa   xxx                 pune         honda            NaN 
1   aaa   yyy               mumbai           tvs            NaN 
2   aaa   xxx                  hyd        maruti            NaN 
3   bbb   xxx                 pune         honda            NaN 
4   bbb   aaa               mumbai           tvs            NaN 

文件2:

  vehicle_Brought_City Vehicle_Brand  Vehicle_price 
0                 pune         honda          50000 
1               mumbai           tvs          40000 
2                  hyd        maruti          45000 

请您参考如下方法:

del df['Vehicle_price'] 
print(df) 
 
dd = pd.merge(df, df1, on=['vehicle_Brought_City', 'Vehicle_Brand']) 
print(dd) 

输出:

  fname lname vehicle_Brought_City Vehicle_Brand  Vehicle_price 
0   aaa   xxx                 pune         honda          50000 
1   aaa   yyy               mumbai           tvs          40000 
2   bbb   aaa               mumbai           tvs          40000 
3   aaa   xxx                  hyd        maruti          45000