两个不同的excel文件以匹配具有相同名称的行

2024-09-29 07:21:32 发布

您现在位置:Python中文网/ 问答频道 /正文

使用python熊猫

我正在尝试在pandas中编写一个条件,它将匹配两个不同excel文件中的两列,这两个文件具有相同的列名和不同的数值。每列有2000行要匹配。你知道吗

条件:

  • 如果最终值=(如果File1(column1value)-File2(column1value)=0,则用1更新该值
  • 如果File1(column1value)-File2(column1value)小于或等于0.2,则保留File1Column1Value
  • 如果(File1Column1)-File2(column1value)大于0.2。用0更新值。你知道吗

https://i.stack.imgur.com/Nx3WA.jpg


Tags: 文件httpscompandasstack条件excelfile1
1条回答
网友
1楼 · 发布于 2024-09-29 07:21:32
    df1 = pd.read_excel('file_name1') # get input from excel files
    df2 = pd.read_excel('file_name2')
    p1 = df1['p1'].values
    p11 = df2['p11'].values
    new_col = [] # we will store desired values here
    for i in range(len(p1)):
       if p1[i] - p11[i] == 0:
          new_col.append(1)
       elif abs(p1[i] - p11[i]) > 0.2:
          new_col.append(0)
       else:
          new_col.append(p1[i])
    df1['new_column'] = new_col # we add new column with our values

也可以删除旧列df.drop('column', axis = 1)

相关问题 更多 >