首页 > 解决方案 > 如何在相似列值上比较两个不同的数据框并将值放入其他数据框

问题描述

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

文本文件 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:

   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

标签: pythonpandasdataframe

解决方案


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

推荐阅读