比较两个csv文件后读取和写入同一个csv文件

2024-04-20 13:00:35 发布

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

我有两个要比较的文件,我有for循环来比较它们,但是我不确定如何继续并使其成为第一个文件中满足if/else语句条件的每一行的数据。你知道吗

date_location = 3
numeric_location = 4


with open('file1.csv', 'r') as f1:
    next(f1)
    with open('file2.csv', 'r') as f2:
        next(f2)
        for i in (f1):
                f1_date = (i.split(',')[date_location])
                f1_number = (i.split(',')[numeric_location])
                for j in (f2):
                        f2_date = (j.split(',')[date_location])
                        f2_number = (j.split(',')[numeric_location])
                        if f1_date == f2_date:
                            if f2_number > f1_number:
#                                print('WIN')
                                continue
                            elif f2_number <= f1_number:
#                                print('lose')
                f2.seek(0, 0)

这是我目前拥有的代码。我想要的是将if循环的结果显示到file1.csv,尽管我无法让它记录我打印到file1.csv的内容。有没有什么方法可以让我在熊猫身上更好地做到这一点?我之前尝试在pandas中创建for循环,但它不允许我对两个文件的数据帧都这样做。你知道吗


Tags: 文件csv数据numberfordateifwith
1条回答
网友
1楼 · 发布于 2024-04-20 13:00:35

您可以创建两个Pandas数据帧并使用np.where()来获得比较。你知道吗

假设您有两个文件,分别称为df1df2。每个df中都有一个score列。然后,你可以通过

result = np.where(df1.score > df2.score, "WIN", "lose")

如果您键入result,它将显示比较结果。你知道吗

您可以使用以下代码在您这边进行实验:

import pandas as pd 
import numpy as np
df1 = pd.util.testing.makeMixedDataFrame()
df2 = pd.util.testing.makeMixedDataFrame()
df3 = np.where(df1.A > df2.B, 'WIN', 'lose')
df3 

更新:

import pandas as pd 
import numpy as np
df1 = pd.util.testing.makeMixedDataFrame()
df2 = pd.util.testing.makeMixedDataFrame()
df3=pd.DataFrame({})
for col in df2.A:
   df3[col] = np.where(df1.A < col, 1,0)
df3

或者这个:

for i in df1.index: # go through file 1 
  r1 = df1.iloc[i] # each time choose a row
  df = df2[df2.D == r1.D] # and choose the rows to compare from file 2, if D matches  
  c = np.where(df.A <= r1.A, "Yes","No") 

  for a in c:
      print (a)

相关问题 更多 >