【问题标题】:How to compare two different Data frames on simile column values and put values to other data frame如何在相似列值上比较两个不同的数据框并将值放入其他数据框
【发布时间】:2019-02-13 09:13:34
【问题描述】:

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

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

【问题讨论】:

  • 你能举例说明你的问题吗?
  • 正如我在数据集中提到的,我有两个文本文件。一个有 fname,lname,vehical_brought_city,Vehical_brought_city,Vehical Brand,Vehicle Price。第一个文本文件没有车辆价格的值。而其他文本文件有车辆带来的城市,车辆品牌和车辆价格。所以我需要做什么取决于组合车辆带来的城市和车辆品牌作为组合车辆价格需要输入文本文件 1。就像在第 0 行,我希望价格为 5000,第 4 行希望价格值为 4000。
  • 好的,我知道你的问题了
  • 在我的实际数据集中,文件 1 有数千条记录,文件 2 只有 30 条记录。两个文件都有 vehical_brought_city 和 Vehical_Brand 基本上我们可以说文件 2 是参考文件。因此,根据 vehical_brought_city 和 Vehical_Brand 的组合,我需要将 Vehical_Price 的值放入文件 1 中。我为此创建了一个数据框,但我被卡住了如何遍历不同的数据框?在这种情况下合并是否也有效?

标签: python pandas dataframe


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多